Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

CurrencyService.php 1.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\{Cache, Http};
  4. class CurrencyService
  5. {
  6. public function getExchangeRate($from, $to)
  7. {
  8. $req_url = 'https://api.exchangerate.host/latest?base=' . $from . '&symbols=' . $to;
  9. $response = Http::get($req_url);
  10. if ($response->successful()) {
  11. $responseData = $response->json();
  12. if (isset($responseData['rates'][$to])) {
  13. return $responseData['rates'][$to];
  14. }
  15. }
  16. return null;
  17. }
  18. public function getCachedExchangeRate(string $defaultCurrencyCode, string $code): ?float
  19. {
  20. $cacheKey = 'currency_data_' . $defaultCurrencyCode . '_' . $code;
  21. $cachedData = Cache::get($cacheKey);
  22. if ($cachedData !== null) {
  23. return $cachedData['rate'];
  24. }
  25. $rate = $this->getExchangeRate($defaultCurrencyCode, $code);
  26. if ($rate !== null) {
  27. $dataToCache = compact('rate');
  28. $expirationTimeInSeconds = 60 * 60 * 24; // 24 hours
  29. Cache::put($cacheKey, $dataToCache, $expirationTimeInSeconds);
  30. }
  31. return $rate;
  32. }
  33. }