1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* (c) itmedia.by <[email protected]> |
4
|
|
|
*/ |
5
|
|
|
|
6
|
|
|
namespace Submarine\NbrbExchangeRatesBundle\Provider; |
7
|
|
|
|
8
|
|
|
|
9
|
|
|
use Doctrine\Common\Cache\Cache; |
10
|
|
|
|
11
|
|
|
class CachedExchangeRateProvider implements ExchangeRatesProviderInterface |
12
|
|
|
{ |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @var ExchangeRatesProviderInterface |
16
|
|
|
*/ |
17
|
|
|
private $provider; |
18
|
|
|
|
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var Cache |
22
|
|
|
*/ |
23
|
|
|
private $cache; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @var int |
27
|
|
|
*/ |
28
|
|
|
private $lifetime; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* CachedExchangeRateProvider constructor. |
32
|
|
|
* @param ExchangeRatesProviderInterface $provider |
33
|
|
|
* @param Cache $cache |
34
|
|
|
* @param int $lifetime |
35
|
|
|
*/ |
36
|
|
|
public function __construct(ExchangeRatesProviderInterface $provider, Cache $cache, $lifetime = 10800) |
37
|
|
|
{ |
38
|
|
|
$this->provider = $provider; |
39
|
|
|
$this->cache = $cache; |
40
|
|
|
$this->lifetime = $lifetime; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* {@inheritdoc} |
46
|
|
|
*/ |
47
|
|
|
public function getAllRatesExchanges(\DateTime $date = null) |
48
|
|
|
{ |
49
|
|
|
$cacheKey = 'submarine_nbrb_' . $date->format('dmy'); |
|
|
|
|
50
|
|
|
|
51
|
|
|
$result = $this->cache->fetch($cacheKey); |
52
|
|
|
if ($result) { |
53
|
|
|
return $result; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
$result = $this->provider->getAllRatesExchanges($date); |
57
|
|
|
$this->cache->save($cacheKey, $result, $this->lifetime); |
58
|
|
|
return $result; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* {@inheritdoc} |
63
|
|
|
*/ |
64
|
|
|
public function getRatesExchanges(array $codes, \DateTime $date = null) |
65
|
|
|
{ |
66
|
|
|
return $this->provider->getRatesExchanges($codes, $date); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* {@inheritdoc} |
71
|
|
|
*/ |
72
|
|
|
public function getRateExchange($code, \DateTime $date = null) |
73
|
|
|
{ |
74
|
|
|
return $this->provider->getRateExchange($code, $date); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* {@inheritdoc} |
79
|
|
|
*/ |
80
|
|
|
public function getRatesExchangesDynamic($code, \DateTime $firstDate, \DateTime $lastDate) |
81
|
|
|
{ |
82
|
|
|
$cacheKey = 'submarine_nbrb_dyn_' . $firstDate->format('dmy') . $lastDate->format('dmy'); |
83
|
|
|
|
84
|
|
|
$result = $this->cache->fetch($cacheKey); |
85
|
|
|
if ($result) { |
86
|
|
|
return $result; |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
$result = $this->provider->getRatesExchangesDynamic($code, $firstDate, $lastDate); |
90
|
|
|
$this->cache->save($cacheKey, $result, $this->lifetime); |
91
|
|
|
return $result; |
92
|
|
|
} |
93
|
|
|
|
94
|
|
|
|
95
|
|
|
} |
If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe: