|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | + |
| 6 | +namespace Exchanger\Service; |
| 7 | + |
| 8 | +use Exchanger\Contract\ExchangeRate; |
| 9 | +use Exchanger\Contract\ExchangeRateQuery; |
| 10 | +use Exchanger\HistoricalExchangeRateQuery; |
| 11 | + |
| 12 | +/** |
| 13 | + * Uses the currency "API" published on JSDelivr. See https://github.com/fawazahmed0/exchange-api |
| 14 | + * |
| 15 | + * @author Jan Böhmer |
| 16 | + */ |
| 17 | +final class FawazahmedCurrencyAPI extends HttpService |
| 18 | +{ |
| 19 | + public const URL_TEMPLATE = "https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@%s/v1/currencies/%s.min.json"; |
| 20 | + |
| 21 | + public function getExchangeRate(ExchangeRateQuery $exchangeQuery): ExchangeRate |
| 22 | + { |
| 23 | + $currencyPair = $exchangeQuery->getCurrencyPair(); |
| 24 | + $base = strtolower($currencyPair->getBaseCurrency()); |
| 25 | + $quote = strtolower($currencyPair->getQuoteCurrency()); |
| 26 | + |
| 27 | + if ($exchangeQuery instanceof HistoricalExchangeRateQuery) { |
| 28 | + $date = $exchangeQuery->getDate()->format('Y-m-d'); |
| 29 | + $url = sprintf(self::URL_TEMPLATE, $date, $base); |
| 30 | + } else { |
| 31 | + $url = sprintf(self::URL_TEMPLATE,'latest', $base); |
| 32 | + } |
| 33 | + |
| 34 | + $content = $this->request($url); |
| 35 | + $data = json_decode($content, true); |
| 36 | + |
| 37 | + if (!isset($data[$base]) || !isset($data[$base][$quote])) { |
| 38 | + throw new \Exchanger\Exception\UnsupportedCurrencyPairException($currencyPair, $this); |
| 39 | + } |
| 40 | + |
| 41 | + $rate = (float)$data[$base][$quote]; |
| 42 | + $date = new \DateTime($data['date']); |
| 43 | + |
| 44 | + return $this->createRate($currencyPair, $rate, $date); |
| 45 | + } |
| 46 | + |
| 47 | + public function supportQuery(ExchangeRateQuery $exchangeQuery): bool |
| 48 | + { |
| 49 | + return !($exchangeQuery instanceof HistoricalExchangeRateQuery && $exchangeQuery->getDate() < new \DateTime('2025-01-01')); |
| 50 | + } |
| 51 | + |
| 52 | + public function getName(): string |
| 53 | + { |
| 54 | + return "fawazahmed_currency_api"; |
| 55 | + } |
| 56 | +} |
0 commit comments