您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

SyncAssociatedModels.php 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. 'account_id' => 'account',
  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. 'income_category_id' => 'incomeCategory',
  41. 'expense_category_id' => 'expenseCategory',
  42. ];
  43. foreach ($diff as $key => $value) {
  44. if (array_key_exists($key, $keyToMethodMap)) {
  45. $method = $keyToMethodMap[$key];
  46. $this->updateEnabledStatus($record->$method(), $value);
  47. }
  48. }
  49. }
  50. private function updateEnabledStatus(BelongsTo $relation, $newValue): void
  51. {
  52. if ($relation->exists()) {
  53. $previousDefault = $relation->getResults();
  54. $previousDefault->update(['enabled' => false]);
  55. }
  56. if ($newValue !== null) {
  57. $newDefault = $relation->getRelated()->newQuery()->where($relation->getOwnerKeyName(), $newValue)->first();
  58. $newDefault?->update(['enabled' => true]);
  59. }
  60. }
  61. }