1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace BenTools\Currency\Provider; |
4
|
|
|
|
5
|
|
|
use BenTools\Currency\Cache\ArrayCache; |
6
|
|
|
use BenTools\Currency\Model\CurrencyInterface; |
7
|
|
|
use BenTools\Currency\Model\ExchangeRateInterface; |
8
|
|
|
use DateTimeInterface; |
9
|
|
|
use Psr\SimpleCache\CacheInterface; |
10
|
|
|
|
11
|
|
|
class PSR16CacheProvider implements ExchangeRateProviderInterface |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var ExchangeRateProviderInterface |
15
|
|
|
*/ |
16
|
|
|
private $exchangeRateProvider; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var CacheInterface |
20
|
|
|
*/ |
21
|
|
|
private $cache; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* PSR16CacheProvider constructor. |
25
|
|
|
* @param ExchangeRateProviderInterface $exchangeRateProvider |
26
|
|
|
* @param CacheInterface|null $cache |
27
|
|
|
*/ |
28
|
|
|
public function __construct( |
29
|
|
|
ExchangeRateProviderInterface $exchangeRateProvider, |
30
|
|
|
CacheInterface $cache = null |
31
|
|
|
) { |
32
|
|
|
$this->exchangeRateProvider = $exchangeRateProvider; |
33
|
|
|
$this->cache = $cache ?? new ArrayCache(); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* @inheritDoc |
38
|
|
|
*/ |
39
|
|
|
public function getExchangeRate(CurrencyInterface $sourceCurrency, CurrencyInterface $targetCurrency, DateTimeInterface $date = null): ExchangeRateInterface |
40
|
|
|
{ |
41
|
|
|
if ($this->cache->has($this->getKey($sourceCurrency, $targetCurrency, $date))) { |
42
|
|
|
return $this->cache->get($this->getKey($sourceCurrency, $targetCurrency, $date)); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
$exchangeRate = $this->exchangeRateProvider->getExchangeRate($sourceCurrency, $targetCurrency, $date); |
46
|
|
|
$this->cache->set($this->getKey($sourceCurrency, $targetCurrency, $date), $exchangeRate); |
47
|
|
|
return $exchangeRate; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @param CurrencyInterface $sourceCurrency |
52
|
|
|
* @param CurrencyInterface $targetCurrency |
53
|
|
|
* @param DateTimeInterface|null $date |
54
|
|
|
* @return string |
55
|
|
|
*/ |
56
|
|
|
private function getKey(CurrencyInterface $sourceCurrency, CurrencyInterface $targetCurrency, DateTimeInterface $date = null): string |
57
|
|
|
{ |
58
|
|
|
if (null === $date) { |
59
|
|
|
return sprintf('%s-%s', $sourceCurrency->getCode(), $targetCurrency->getCode()); |
60
|
|
|
} |
61
|
|
|
return sprintf('%s-%s-%s', $sourceCurrency->getCode(), $targetCurrency->getCode(), $date->format('U')); |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|