1 | <?php |
||
17 | class ChainCache implements Cache |
||
18 | { |
||
19 | use MultiCacheTrait; |
||
20 | |||
21 | /** |
||
22 | * Stored items |
||
23 | * |
||
24 | * @var Cache[] |
||
25 | */ |
||
26 | private $cache = []; |
||
27 | |||
28 | /** |
||
29 | * Pushes a cache in the chain |
||
30 | * |
||
31 | * @param Cache $cache |
||
32 | * |
||
33 | * @return $this |
||
34 | */ |
||
35 | 1 | public function pushCache(Cache $cache) |
|
41 | |||
42 | /** |
||
43 | * {@inheritdoc} |
||
44 | */ |
||
45 | 1 | public function set($key, $item, $timeToLive = null) |
|
46 | { |
||
47 | 1 | $success = true; |
|
48 | 1 | foreach ($this->cache as $cache) { |
|
49 | 1 | $success = $success && $cache->set($key, $item, $timeToLive); |
|
50 | } |
||
51 | |||
52 | 1 | return $success; |
|
53 | } |
||
54 | |||
55 | /** |
||
56 | * {@inheritdoc} |
||
57 | */ |
||
58 | 1 | public function has($key) |
|
59 | { |
||
60 | 1 | foreach ($this->cache as $cache) { |
|
61 | 1 | if ($cache->has($key)) { |
|
62 | 1 | return true; |
|
63 | } |
||
64 | } |
||
65 | |||
66 | 1 | return false; |
|
67 | } |
||
68 | |||
69 | /** |
||
70 | * {@inheritdoc} |
||
71 | */ |
||
72 | 1 | public function get($key, $default = null) |
|
73 | { |
||
74 | 1 | foreach ($this->cache as $index => $cache) { |
|
75 | 1 | $item = $cache->get($key); |
|
76 | 1 | if ($item) { |
|
77 | 1 | $this->populatePreviousCaches($index, $key, $item, $cache->getTimeToLive($key)); |
|
78 | |||
79 | 1 | return $item; |
|
80 | } |
||
81 | } |
||
82 | |||
83 | 1 | return $default; |
|
84 | } |
||
85 | |||
86 | /** |
||
87 | * {@inheritdoc} |
||
88 | */ |
||
89 | 1 | public function demand($key) |
|
98 | |||
99 | /** |
||
100 | * {@inheritdoc} |
||
101 | */ |
||
102 | 1 | public function delete($key) |
|
111 | |||
112 | /** |
||
113 | * {@inheritdoc} |
||
114 | */ |
||
115 | 1 | public function flush() |
|
124 | |||
125 | /** |
||
126 | * Gets the remaining time to live for an item |
||
127 | * |
||
128 | * @param $key |
||
129 | * |
||
130 | * @return int|null |
||
131 | */ |
||
132 | 1 | public function getTimeToLive($key) |
|
143 | |||
144 | /** |
||
145 | * @param string $index |
||
146 | * @param string $key |
||
147 | * @param string $item |
||
148 | * @param int|null $timeToLive |
||
149 | */ |
||
150 | 1 | private function populatePreviousCaches($index, $key, $item, $timeToLive) |
|
156 | } |
||
157 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.