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.

CurrencyService.php 1.2KB

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