nuri60
class ExchangeRateData implements Arrayable
{
public function __construct(
public string $adapter,
public string $currency,
public float $buying,
public float $selling,
)
{}
public function toArray(): array
{
return [
'adapter' => $this->adapter,
'currency' => $this->currency,
'buying' => $this->buying,
'selling' => $this->selling,
];
}
}
interface ExchangeRateProviderAdapter
{
public function fetch(string $currency): ExchangeRateData;
}
class TCMBAdapter implements ExchangeRateProviderAdapter
{
public const NAME = 'tcmb';
public function fetch(string $currency): ExchangeRateData
{
$response = Http::get('https://www.tcmb.gov.tr/kurlar/today.xml')
->throw()
->json();
$buying = //$response...
$selling = //$response...
return new ExchangeRateData(static::NAME, $currency, $buying, $selling);
}
}
class SampleAdapter implements ExchangeRateProviderAdapter
{
public const NAME = 'sample';
public function fetch($currency): ExchangeRateData
{
$response = Http::get('https://domain.com/exchange-rates')
->throw()
->json();
$buying = //$response...
$selling = //$response...
return new ExchangeRateData(static::NAME, $currency, $buying, $selling);
}
}
interface EchangeRateServiceInterface
{
public function fetch(string $currency, ExchangeRateProviderAdapter $adapter): ExchangeRateData;
public function fetchAll(string $currency, ?array $adapters = null): array;
}
class EchangeRateService implements EchangeRateServiceInterface
{
public function fetch(string $currency, ExchangeRateProviderAdapter $adapter): ExchangeRateData
{
return $adapter->fetch($currency);
}
public function fetchAll(string $currency, ?array $adapters = null): array
{
$adapters ??= [
new TCMBAdapter,
new SampleAdapter,
];
$rates = [];
foreach($adapters as $adapter) {
$rates[$adapter::NAME] = $this->fetch($currency, $adapter)
->toArray();
}
return $rates;
}
}
public function rates(EchangeRateServiceInterface $echangeRateService): array
{
return $echangeRateService->fetchAll('USD');
}
/*
{
"tcmb": {
"adapter": "tcmb",
"currency": "USD",
"buying": 26.1446,
"selling": 26.1917
},
"sample": {
"adapter": "sample",
"currency": "USD",
"buying": 26.1446,
"selling": 26.1917
}
}
*/