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

CurrencyService.php 4.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. <?php
  2. namespace App\Services;
  3. use App\Contracts\CurrencyHandler;
  4. use GuzzleHttp\Client;
  5. use GuzzleHttp\Exception\GuzzleException;
  6. use Illuminate\Support\Facades\Cache;
  7. use Illuminate\Support\Facades\Log;
  8. class CurrencyService implements CurrencyHandler
  9. {
  10. public function __construct(
  11. protected ?string $apiKey,
  12. protected ?string $baseUrl,
  13. protected Client $client
  14. ) {}
  15. /**
  16. * Determine if the Currency Exchange Rate feature is enabled.
  17. */
  18. public function isEnabled(): bool
  19. {
  20. return filled($this->apiKey) && filled($this->baseUrl);
  21. }
  22. public function getSupportedCurrencies(): ?array
  23. {
  24. if (! $this->isEnabled()) {
  25. return null;
  26. }
  27. return Cache::remember('supported_currency_codes', now()->addMonth(), function () {
  28. $response = $this->client->get("{$this->baseUrl}/{$this->apiKey}/codes");
  29. if ($response->getStatusCode() === 200) {
  30. $responseData = json_decode($response->getBody()->getContents(), true);
  31. if ($responseData['result'] === 'success' && filled($responseData['supported_codes'])) {
  32. return array_column($responseData['supported_codes'], 0);
  33. }
  34. }
  35. Log::error('Failed to retrieve supported currencies from Currency API', [
  36. 'status_code' => $response->getStatusCode(),
  37. 'response_body' => $response->getBody()->getContents(),
  38. ]);
  39. return null;
  40. });
  41. }
  42. public function getExchangeRates(string $baseCurrency, array $targetCurrencies): ?array
  43. {
  44. $cacheKey = "currency_rates_{$baseCurrency}";
  45. $cachedRates = Cache::get($cacheKey);
  46. if (Cache::missing($cachedRates)) {
  47. $cachedRates = $this->updateCurrencyRatesCache($baseCurrency);
  48. if (empty($cachedRates)) {
  49. return null;
  50. }
  51. }
  52. $filteredRates = array_intersect_key($cachedRates, array_flip($targetCurrencies));
  53. $filteredRates = array_filter($filteredRates);
  54. $filteredCurrencies = array_keys($filteredRates);
  55. $missingCurrencies = array_diff($targetCurrencies, $filteredCurrencies);
  56. if (filled($missingCurrencies)) {
  57. return null;
  58. }
  59. return $filteredRates;
  60. }
  61. public function getCachedExchangeRates(string $baseCurrency, array $targetCurrencies): ?array
  62. {
  63. if ($this->isEnabled()) {
  64. return $this->getExchangeRates($baseCurrency, $targetCurrencies);
  65. }
  66. return null;
  67. }
  68. public function getCachedExchangeRate(string $baseCurrency, string $targetCurrency): ?float
  69. {
  70. $rates = $this->getCachedExchangeRates($baseCurrency, [$targetCurrency]);
  71. if (isset($rates[$targetCurrency])) {
  72. return (float) $rates[$targetCurrency];
  73. }
  74. return null;
  75. }
  76. public function updateCurrencyRatesCache(string $baseCurrency): ?array
  77. {
  78. try {
  79. $response = $this->client->get("{$this->baseUrl}/{$this->apiKey}/latest/{$baseCurrency}");
  80. if ($response->getStatusCode() === 200) {
  81. $responseData = json_decode($response->getBody()->getContents(), true);
  82. if ($responseData['result'] === 'success' && isset($responseData['conversion_rates'])) {
  83. Cache::put("currency_rates_{$baseCurrency}", $responseData['conversion_rates'], now()->addDay());
  84. return $responseData['conversion_rates'];
  85. }
  86. $errorType = $responseData['error-type'] ?? 'unknown';
  87. Log::error('API returned error', [
  88. 'error_type' => $errorType,
  89. 'response_body' => $responseData,
  90. ]);
  91. } else {
  92. Log::error('Failed to retrieve exchange rates from Currency API', [
  93. 'status_code' => $response->getStatusCode(),
  94. 'response_body' => $response->getBody()->getContents(),
  95. ]);
  96. }
  97. } catch (GuzzleException $e) {
  98. Log::error('Failed to retrieve exchange rates from Currency API', [
  99. 'message' => $e->getMessage(),
  100. 'code' => $e->getCode(),
  101. ]);
  102. }
  103. return null;
  104. }
  105. }