PSR16CacheProvider::getExchangeRate()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
cc 2
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
final 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
48
        return $exchangeRate;
49
    }
50
51
    /**
52
     * @param CurrencyInterface      $sourceCurrency
53
     * @param CurrencyInterface      $targetCurrency
54
     * @param DateTimeInterface|null $date
55
     * @return string
56
     */
57
    private function getKey(CurrencyInterface $sourceCurrency, CurrencyInterface $targetCurrency, DateTimeInterface $date = null): string
58
    {
59
        if (null === $date) {
60
            return sprintf('%s-%s', $sourceCurrency->getCode(), $targetCurrency->getCode());
61
        }
62
        return sprintf('%s-%s-%s', $sourceCurrency->getCode(), $targetCurrency->getCode(), $date->format('U'));
63
    }
64
}
65