Skip to content

Commit b534808

Browse files
committed
Added Fawazahmed Currency "API"
1 parent f03b85b commit b534808

File tree

5 files changed

+452
-0
lines changed

5 files changed

+452
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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+
}

src/Service/Registry.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ public static function getServices(): array
5757
'apilayer_currency_data' => ApiLayer\CurrencyData::class,
5858
'apilayer_exchange_rates_data' => ApiLayer\ExchangeRatesData::class,
5959
'frankfurter' => Frankfurter::class,
60+
'fawazahmed_currency_api' => FawazahmedCurrencyAPI::class,
6061
];
6162
}
6263
}

0 commit comments

Comments
 (0)