You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UpdateCurrencyRates.php 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace App\Listeners;
  3. use App\Contracts\CurrencyHandler;
  4. use App\Events\DefaultCurrencyChanged;
  5. use App\Facades\Forex;
  6. use App\Models\Setting\Currency;
  7. use Illuminate\Support\Facades\DB;
  8. readonly class UpdateCurrencyRates
  9. {
  10. /**
  11. * Create the event listener.
  12. */
  13. public function __construct(private CurrencyHandler $currencyService)
  14. {
  15. //
  16. }
  17. /**
  18. * Handle the event.
  19. */
  20. public function handle(DefaultCurrencyChanged $event): void
  21. {
  22. DB::transaction(function () use ($event) {
  23. $defaultCurrency = $event->currency;
  24. if (bccomp((string) $defaultCurrency->rate, '1.0', 8) !== 0) {
  25. $defaultCurrency->update(['rate' => 1]);
  26. }
  27. if (Forex::isEnabled()) {
  28. $this->updateOtherCurrencyRates($defaultCurrency);
  29. }
  30. });
  31. }
  32. private function updateOtherCurrencyRates(Currency $defaultCurrency): void
  33. {
  34. $targetCurrencies = Currency::where('code', '!=', $defaultCurrency->code)
  35. ->pluck('code')
  36. ->toArray();
  37. $exchangeRates = $this->currencyService->getCachedExchangeRates($defaultCurrency->code, $targetCurrencies);
  38. foreach ($exchangeRates as $currencyCode => $newRate) {
  39. $currency = Currency::where('code', $currencyCode)->first();
  40. if ($currency && bccomp((string) $currency->rate, (string) $newRate, 8) !== 0) {
  41. $currency->update(['rate' => $newRate]);
  42. }
  43. }
  44. }
  45. }