Refactor exchange rate providers into driver-based architecture

Replace duplicated switch/case blocks across 4 methods with a clean
abstract driver pattern:

- ExchangeRateDriver (abstract): defines getExchangeRate(),
  getSupportedCurrencies(), validateConnection()
- CurrencyFreakDriver, CurrencyLayerDriver, OpenExchangeRateDriver,
  CurrencyConverterDriver: concrete implementations
- ExchangeRateDriverFactory: resolves driver name to class, with
  register() method for module extensibility

Delete ExchangeRateProvidersTrait — all logic now lives in driver
classes and ExchangeRateProviderService. Adding a new exchange rate
provider only requires implementing ExchangeRateDriver and calling
ExchangeRateDriverFactory::register() in a module service provider.
This commit is contained in:
Darko Gjorgjijoski
2026-04-03 20:24:03 +02:00
parent 8f29e8f5de
commit 85b62dfdf8
10 changed files with 354 additions and 280 deletions

View File

@@ -0,0 +1,52 @@
<?php
namespace App\Services\ExchangeRate;
use Illuminate\Support\Facades\Http;
class OpenExchangeRateDriver extends ExchangeRateDriver
{
private string $baseUrl = 'https://openexchangerates.org/api';
public function getExchangeRate(string $baseCurrency, string $targetCurrency): array
{
$url = "{$this->baseUrl}/latest.json?app_id={$this->apiKey}&base={$baseCurrency}&symbols={$targetCurrency}";
$response = Http::get($url)->json();
if (array_key_exists('error', $response)) {
throw new ExchangeRateException($response['description'], $response['message']);
}
return array_values($response['rates']);
}
public function getSupportedCurrencies(): array
{
$url = "{$this->baseUrl}/currencies.json";
$response = Http::get($url)->json();
if ($response == null) {
throw new ExchangeRateException('Server not responding', 'server_error');
}
$checkKey = $this->validateConnection();
return array_keys($response);
}
public function validateConnection(): array
{
$url = "{$this->baseUrl}/latest.json?app_id={$this->apiKey}&base=INR&symbols=USD";
$response = Http::get($url)->json();
if (array_key_exists('error', $response)) {
if ($response['status'] == 401) {
throw new ExchangeRateException('Please Enter Valid Provider Key.', 'invalid_key');
}
throw new ExchangeRateException($response['description'], $response['message']);
}
return array_values($response['rates']);
}
}