|
| 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\Contract\HistoricalExchangeRateQuery as HistoricalExchangeRateQueryContract; |
| 11 | +use Exchanger\Exception\UnsupportedCurrencyPairException; |
| 12 | + |
| 13 | +/** |
| 14 | + * Uses the free API at https://frankfurter.dev/ |
| 15 | + */ |
| 16 | +final class Frankfurter extends HttpService |
| 17 | +{ |
| 18 | + |
| 19 | + private const BASE_URL = "https://api.frankfurter.dev/v1/"; |
| 20 | + private const SUPPORTED_CURRENCIES = [ |
| 21 | + 'AUD', 'BGN', 'BRL', 'CAD', 'CHF', 'CNY', 'CZK', 'DKK', 'EUR', |
| 22 | + 'GBP', 'HKD', 'HUF', 'IDR', 'ILS', 'INR', 'ISK', 'JPY', |
| 23 | + 'KRW', 'MXN', 'MYR', 'NOK', 'NZD', 'PHP', 'PLN', 'RON', |
| 24 | + 'SEK', 'SGD', 'THB', 'TRY', 'USD', 'ZAR' |
| 25 | + ]; |
| 26 | + |
| 27 | + public function supportQuery(ExchangeRateQuery $exchangeQuery): bool |
| 28 | + { |
| 29 | + $currencyPair = $exchangeQuery->getCurrencyPair(); |
| 30 | + return in_array($currencyPair->getBaseCurrency(), self::SUPPORTED_CURRENCIES) && |
| 31 | + in_array($currencyPair->getQuoteCurrency(), self::SUPPORTED_CURRENCIES); |
| 32 | + } |
| 33 | + |
| 34 | + public function getName(): string |
| 35 | + { |
| 36 | + return 'frankfurter'; |
| 37 | + } |
| 38 | + |
| 39 | + public function getExchangeRate(ExchangeRateQuery $exchangeQuery): ExchangeRate |
| 40 | + { |
| 41 | + $currencyPair = $exchangeQuery->getCurrencyPair(); |
| 42 | + $base = $currencyPair->getBaseCurrency(); |
| 43 | + $quote = $currencyPair->getQuoteCurrency(); |
| 44 | + |
| 45 | + if ($exchangeQuery instanceof HistoricalExchangeRateQueryContract) { |
| 46 | + $date = $exchangeQuery->getDate()->format('Y-m-d'); |
| 47 | + $url = self::BASE_URL . "{$date}?base={$base}&symbols={$quote}"; |
| 48 | + } else { |
| 49 | + $url = self::BASE_URL . "latest?base={$base}&symbols={$quote}"; |
| 50 | + } |
| 51 | + |
| 52 | + $content = $this->request($url); |
| 53 | + $data = json_decode($content, true); |
| 54 | + |
| 55 | + if (!isset($data['rates'][$quote])) { |
| 56 | + throw new UnsupportedCurrencyPairException($currencyPair, $this); |
| 57 | + } |
| 58 | + |
| 59 | + $rate = (float)$data['rates'][$quote]; |
| 60 | + $date = new \DateTime($data['date']); |
| 61 | + |
| 62 | + return $this->createRate($currencyPair, $rate, $date); |
| 63 | + } |
| 64 | +} |
0 commit comments