Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add CurrencyBeacon driver #149

Merged
merged 4 commits into from
Feb 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,7 @@ The following drivers are available with the package:

| API Service | Driver name | API URL |
|-------------------------|---------------------------|---------------------------------------------------------|
| CurrencyBeacon | `currency-beacon` | https://currencybeacon.com/ |
| Exchange Rates API IO | `exchange-rates-api-io` | https://exchangeratesapi.io/ |
| Exchange Rates Data API | `exchange-rates-data-api` | https://apilayer.com/marketplace/exchangerates_data-api |
| Exchange Rate Host | `exchange-rate-host` | https://exchangerate.host |
Expand Down
6 changes: 6 additions & 0 deletions src/Classes/ExchangeRate.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace AshAllenDesign\LaravelExchangeRates\Classes;

use AshAllenDesign\LaravelExchangeRates\Drivers\CurrencyBeacon\CurrencyBeaconDriver;
use AshAllenDesign\LaravelExchangeRates\Drivers\ExchangeRateHost\ExchangeRateHostDriver;
use AshAllenDesign\LaravelExchangeRates\Drivers\ExchangeRatesApiIo\ExchangeRatesApiIoDriver;
use AshAllenDesign\LaravelExchangeRates\Drivers\ExchangeRatesDataApi\ExchangeRatesDataApiDriver;
Expand All @@ -12,6 +13,11 @@

class ExchangeRate extends Manager
{
public function createCurrencyBeaconDriver(): ExchangeRateDriver
{
return new CurrencyBeaconDriver();
}

public function createExchangeRatesDataApiDriver(): ExchangeRateDriver
{
return new ExchangeRatesDataApiDriver();
Expand Down
218 changes: 218 additions & 0 deletions src/Drivers/CurrencyBeacon/CurrencyBeaconDriver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
<?php

declare(strict_types=1);

namespace AshAllenDesign\LaravelExchangeRates\Drivers\CurrencyBeacon;

use AshAllenDesign\LaravelExchangeRates\Classes\CacheRepository;
use AshAllenDesign\LaravelExchangeRates\Drivers\Support\SharedDriverLogicHandler;
use AshAllenDesign\LaravelExchangeRates\Interfaces\ExchangeRateDriver;
use Carbon\Carbon;
use Illuminate\Http\Client\RequestException;

/**
* @see https://currencybeacon.com
*/
class CurrencyBeaconDriver implements ExchangeRateDriver
{
private CacheRepository $cacheRepository;

private SharedDriverLogicHandler $sharedDriverLogicHandler;

public function __construct(?RequestBuilder $requestBuilder = null, ?CacheRepository $cacheRepository = null)
{
$requestBuilder = $requestBuilder ?? new RequestBuilder();
$this->cacheRepository = $cacheRepository ?? new CacheRepository();

$this->sharedDriverLogicHandler = new SharedDriverLogicHandler(
$requestBuilder,
$this->cacheRepository,
);
}

/**
* {@inheritDoc}
*/
public function currencies(): array
{
$cacheKey = 'currencies';

if ($cachedExchangeRate = $this->sharedDriverLogicHandler->attemptToResolveFromCache($cacheKey)) {
return $cachedExchangeRate;
}

$response = $this->sharedDriverLogicHandler
->getRequestBuilder()
->makeRequest('/currencies', ['type' => 'fiat']);

/** @var array<int,array<string,string|int|bool>> $currenciesFromResponse */
$currenciesFromResponse = $response->get('response');

$currencies = collect($currenciesFromResponse)->pluck('short_code')->toArray();

$this->sharedDriverLogicHandler->attemptToStoreInCache($cacheKey, $currencies);

return $currencies;
}

/**
* {@inheritDoc}
*/
public function exchangeRate(string $from, array|string $to, ?Carbon $date = null): float|array
{
$this->sharedDriverLogicHandler->validateExchangeRateInput($from, $to, $date);

if ($from === $to) {
return 1.0;
}

$cacheKey = $this->cacheRepository->buildCacheKey($from, $to, $date ?? Carbon::now());

if ($cachedExchangeRate = $this->sharedDriverLogicHandler->attemptToResolveFromCache($cacheKey)) {
// If the exchange rate has been retrieved from the cache as a
// string (e.g. "1.23"), then cast it to a float (e.g. 1.23).
// If we have retrieved the rates for many currencies, it
// will be an array of floats, so just return it.
return is_string($cachedExchangeRate)
? (float) $cachedExchangeRate
: $cachedExchangeRate;
}

$symbols = is_string($to) ? $to : implode(',', $to);
$queryParams = ['base' => $from, 'symbols' => $symbols];

if ($date) {
$queryParams['date'] = $date->format('Y-m-d');
}

$url = $date ? '/historical' : '/latest';

/** @var array<string,float> $response */
$response = $this->sharedDriverLogicHandler
->getRequestBuilder()
->makeRequest($url, $queryParams)
->rates();

$exchangeRate = is_string($to)
? $response[$to]
: $response;

$this->sharedDriverLogicHandler->attemptToStoreInCache($cacheKey, $exchangeRate);

return $exchangeRate;
}

/**
* {@inheritDoc}
*/
public function exchangeRateBetweenDateRange(
string $from,
array|string $to,
Carbon $date,
Carbon $endDate
): array {
$this->sharedDriverLogicHandler->validateExchangeRateBetweenDateRangeInput($from, $to, $date, $endDate);

$cacheKey = $this->cacheRepository->buildCacheKey($from, $to, $date, $endDate);

if ($cachedExchangeRate = $this->sharedDriverLogicHandler->attemptToResolveFromCache($cacheKey)) {
return $cachedExchangeRate;
}

$conversions = $from === $to
? $this->sharedDriverLogicHandler->exchangeRateDateRangeResultWithSameCurrency($date, $endDate)
: $this->makeRequestForExchangeRates($from, $to, $date, $endDate);

$this->sharedDriverLogicHandler->attemptToStoreInCache($cacheKey, $conversions);

return $conversions;
}

/**
* {@inheritDoc}
*/
public function convert(int $value, string $from, array|string $to, ?Carbon $date = null): float|array
{
return $this->sharedDriverLogicHandler->convertUsingRates(
$this->exchangeRate($from, $to, $date),
$to,
$value,
);
}

/**
* {@inheritDoc}
*/
public function convertBetweenDateRange(
int $value,
string $from,
array|string $to,
Carbon $date,
Carbon $endDate
): array {
return $this->sharedDriverLogicHandler->convertUsingRatesForDateRange(
$this->exchangeRateBetweenDateRange($from, $to, $date, $endDate),
$to,
$value,
);
}

/**
* {@inheritDoc}
*/
public function shouldCache(bool $shouldCache = true): ExchangeRateDriver
{
$this->sharedDriverLogicHandler->shouldCache($shouldCache);

return $this;
}

/**
* {@inheritDoc}
*/
public function shouldBustCache(bool $bustCache = true): ExchangeRateDriver
{
$this->sharedDriverLogicHandler->shouldBustCache($bustCache);

return $this;
}

/**
* Make a request to the exchange rates API to get the exchange rates between a
* date range. If only one currency is being used, we flatten the array to
* remove currency symbol before returning it.
*
* @param string|string[] $to
* @return array<string, float>|array<string, array<string, float>>
*
* @throws RequestException
*/
private function makeRequestForExchangeRates(string $from, string|array $to, Carbon $date, Carbon $endDate): array
{
$symbols = is_string($to) ? $to : implode(',', $to);

/** @var Response $result */
$result = $this->sharedDriverLogicHandler
->getRequestBuilder()
->makeRequest('/timeseries', [
'base' => $from,
'start_date' => $date->format('Y-m-d'),
'end_date' => $endDate->format('Y-m-d'),
'symbols' => $symbols,
]);

$conversions = $result->timeSeries();

foreach ($conversions as $rateDate => $rates) {
$ratesForDay = is_string($to)
? $rates[$to]
: $rates;

$conversions[$rateDate] = $ratesForDay;
}

ksort($conversions);

return $conversions;
}
}
42 changes: 42 additions & 0 deletions src/Drivers/CurrencyBeacon/RequestBuilder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

namespace AshAllenDesign\LaravelExchangeRates\Drivers\CurrencyBeacon;

use AshAllenDesign\LaravelExchangeRates\Interfaces\RequestSender;
use AshAllenDesign\LaravelExchangeRates\Interfaces\ResponseContract;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;

class RequestBuilder implements RequestSender
{
private const BASE_URL = 'api.currencybeacon.com/v1';

private string $apiKey;

public function __construct()
{
$this->apiKey = config('laravel-exchange-rates.api_key');
}

/**
* Make an API request to the CurrencyBeacon API.
*
* @param array<string, string> $queryParams
*
* @throws RequestException
*/
public function makeRequest(string $path, array $queryParams = []): ResponseContract
{
$protocol = config('laravel-exchange-rates.https') ? 'https://' : 'http://';

$rawResponse = Http::baseUrl($protocol.self::BASE_URL)
->get(
$path,
array_merge(['api_key' => $this->apiKey], $queryParams)
)
->throw()
->json();

return new Response($rawResponse);
}
}
32 changes: 32 additions & 0 deletions src/Drivers/CurrencyBeacon/Response.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace AshAllenDesign\LaravelExchangeRates\Drivers\CurrencyBeacon;

use AshAllenDesign\LaravelExchangeRates\Interfaces\ResponseContract;

class Response implements ResponseContract
{
public function __construct(private array $rawResponse)
{
}

public function get(string $key): mixed
{
return data_get($this->rawResponse, $key);
}

public function rates(): array
{
return $this->get('response.rates');
}

public function timeSeries(): array
{
return $this->get('response');
}

public function raw(): mixed
{
return $this->rawResponse;
}
}
2 changes: 2 additions & 0 deletions tests/Unit/Classes/ExchangeRateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace AshAllenDesign\LaravelExchangeRates\Tests\Unit\Classes;

use AshAllenDesign\LaravelExchangeRates\Classes\ExchangeRate;
use AshAllenDesign\LaravelExchangeRates\Drivers\CurrencyBeacon\CurrencyBeaconDriver;
use AshAllenDesign\LaravelExchangeRates\Drivers\ExchangeRateHost\ExchangeRateHostDriver;
use AshAllenDesign\LaravelExchangeRates\Drivers\ExchangeRatesApiIo\ExchangeRatesApiIoDriver;
use AshAllenDesign\LaravelExchangeRates\Drivers\ExchangeRatesDataApi\ExchangeRatesDataApiDriver;
Expand Down Expand Up @@ -49,6 +50,7 @@ public function validDriversProvider(): array
['exchange-rates-api-io', ExchangeRatesApiIoDriver::class],
['exchange-rates-data-api', ExchangeRatesDataApiDriver::class],
['exchange-rate-host', ExchangeRateHostDriver::class],
['currency-beacon', CurrencyBeaconDriver::class],
];
}
}
Loading
Loading