Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

SyncAssociatedModels.php 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace App\Listeners;
  3. use App\Events\CompanyDefaultUpdated;
  4. use App\Models\Setting\CompanyDefault;
  5. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  6. use Illuminate\Support\Facades\DB;
  7. class SyncAssociatedModels
  8. {
  9. /**
  10. * Create the event listener.
  11. */
  12. public function __construct()
  13. {
  14. //
  15. }
  16. /**
  17. * Handle the event.
  18. */
  19. public function handle(CompanyDefaultUpdated $event): void
  20. {
  21. DB::transaction(function () use ($event) {
  22. $this->syncAssociatedModels($event);
  23. }, 5);
  24. }
  25. private function syncAssociatedModels(CompanyDefaultUpdated $event): void
  26. {
  27. /** @var CompanyDefault $record */
  28. $record = $event->record;
  29. $data = $event->data;
  30. $record_array = array_map('strval', $record->toArray());
  31. $data = array_map('strval', $data);
  32. $diff = array_diff_assoc($data, $record_array);
  33. $keyToMethodMap = [
  34. 'bank_account_id' => 'bankAccount',
  35. 'currency_code' => 'currency',
  36. 'sales_tax_id' => 'salesTax',
  37. 'purchase_tax_id' => 'purchaseTax',
  38. 'sales_discount_id' => 'salesDiscount',
  39. 'purchase_discount_id' => 'purchaseDiscount',
  40. ];
  41. foreach ($diff as $key => $value) {
  42. if (array_key_exists($key, $keyToMethodMap)) {
  43. $method = $keyToMethodMap[$key];
  44. $this->updateEnabledStatus($record->$method(), $value);
  45. }
  46. }
  47. }
  48. private function updateEnabledStatus(BelongsTo $relation, $newValue): void
  49. {
  50. if ($relation->exists()) {
  51. $previousDefault = $relation->getResults();
  52. $previousDefault->update(['enabled' => false]);
  53. }
  54. if ($newValue !== null) {
  55. $newDefault = $relation->getRelated()->newQuery()->where($relation->getOwnerKeyName(), $newValue)->first();
  56. $newDefault?->update(['enabled' => true]);
  57. }
  58. }
  59. }