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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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(
  14. private CurrencyHandler $currencyService
  15. ) {}
  16. /**
  17. * Handle the event.
  18. */
  19. public function handle(DefaultCurrencyChanged $event): void
  20. {
  21. DB::transaction(function () use ($event) {
  22. $defaultCurrency = $event->currency;
  23. if (bccomp((string) $defaultCurrency->rate, '1.0', 8) !== 0) {
  24. $defaultCurrency->update(['rate' => 1]);
  25. }
  26. if (Forex::isEnabled()) {
  27. $this->updateOtherCurrencyRates($defaultCurrency);
  28. }
  29. });
  30. }
  31. private function updateOtherCurrencyRates(Currency $defaultCurrency): void
  32. {
  33. $targetCurrencies = Currency::where('code', '!=', $defaultCurrency->code)
  34. ->pluck('code')
  35. ->toArray();
  36. $exchangeRates = $this->currencyService->getCachedExchangeRates($defaultCurrency->code, $targetCurrencies);
  37. foreach ($exchangeRates as $currencyCode => $newRate) {
  38. $currency = Currency::where('code', $currencyCode)->first();
  39. if ($currency && bccomp((string) $currency->rate, (string) $newRate, 8) !== 0) {
  40. $currency->update(['rate' => $newRate]);
  41. }
  42. }
  43. }
  44. }