選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

SyncAssociatedModels.php 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. ];
  36. foreach ($diff as $key => $value) {
  37. if (array_key_exists($key, $keyToMethodMap)) {
  38. $method = $keyToMethodMap[$key];
  39. $this->updateEnabledStatus($record->$method(), $value);
  40. }
  41. }
  42. }
  43. private function updateEnabledStatus(BelongsTo $relation, $newValue): void
  44. {
  45. if ($relation->exists()) {
  46. $previousDefault = $relation->getResults();
  47. $previousDefault->update(['enabled' => false]);
  48. }
  49. if ($newValue !== null) {
  50. $newDefault = $relation->getRelated()->newQuery()->where($relation->getOwnerKeyName(), $newValue)->first();
  51. $newDefault?->update(['enabled' => true]);
  52. }
  53. }
  54. }