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

SyncAssociatedModels.php 2.1KB

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