Completed
Push — master ( ca4577...8a3c51 )
by BENOIT
02:50
created

PSR16CacheProvider::getExchangeRate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 3
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