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.3KB

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