1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace BenTools\Currency\Provider; |
4
|
|
|
|
5
|
|
|
use BenTools\Currency\Model\CurrencyInterface; |
6
|
|
|
use BenTools\Currency\Model\ExchangeRateInterface; |
7
|
|
|
use BenTools\Currency\Model\ExchangeRateNotFoundException; |
8
|
|
|
use DateTimeInterface; |
9
|
|
|
|
10
|
|
|
class ChainedExchangeRateProvider implements ExchangeRateProviderInterface |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* @var ExchangeRateProviderInterface[] |
14
|
|
|
*/ |
15
|
|
|
private $exchangeRateProviders = []; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* ChainedExchangeRateProvider constructor. |
19
|
|
|
* @param ExchangeRateProviderInterface[] $exchangeRateProviders |
20
|
|
|
*/ |
21
|
|
|
public function __construct(array $exchangeRateProviders) |
22
|
|
|
{ |
23
|
|
|
$this->exchangeRateProviders = (function (ExchangeRateProviderInterface ...$exchangeRateProviders) { |
24
|
|
|
return $exchangeRateProviders; |
25
|
|
|
})(...$exchangeRateProviders); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @inheritDoc |
30
|
|
|
*/ |
31
|
|
|
public function getExchangeRate(CurrencyInterface $sourceCurrency, CurrencyInterface $targetCurrency, DateTimeInterface $date = null): ExchangeRateInterface |
32
|
|
|
{ |
33
|
|
|
foreach ($this->exchangeRateProviders as $exchangeRateProvider) { |
34
|
|
|
try { |
35
|
|
|
return $exchangeRateProvider->getExchangeRate($sourceCurrency, $targetCurrency, $date); |
36
|
|
|
} catch (ExchangeRateNotFoundException $e) { |
37
|
|
|
continue; |
38
|
|
|
} |
39
|
|
|
} |
40
|
|
|
throw new ExchangeRateNotFoundException($sourceCurrency, $targetCurrency); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param ExchangeRateProviderInterface[] ...$exchangeRateProviders |
45
|
|
|
* @return AverageExchangeRateProvider |
46
|
|
|
*/ |
47
|
|
|
public function withProviders(ExchangeRateProviderInterface ...$exchangeRateProviders): self |
48
|
|
|
{ |
49
|
|
|
$clone = clone $this; |
50
|
|
|
foreach ($exchangeRateProviders as $exchangeRateProvider) { |
51
|
|
|
$clone->exchangeRateProviders[] = $exchangeRateProvider; |
52
|
|
|
} |
53
|
|
|
return $clone; |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|