1 | <?php |
||
17 | class ArrayCache implements Cache |
||
18 | { |
||
19 | /** |
||
20 | * Stored items |
||
21 | * |
||
22 | * @var array |
||
23 | */ |
||
24 | private $items = []; |
||
25 | |||
26 | /** |
||
27 | * {@inheritdoc} |
||
28 | */ |
||
29 | public function set($key, $value, $timeToLive = 0) |
||
30 | { |
||
31 | $this->items[$key] = [ |
||
32 | 'value' => $value, |
||
33 | 'expireTime' => $timeToLive === 0 ? $timeToLive : time() + $timeToLive, |
||
34 | ]; |
||
35 | } |
||
36 | |||
37 | /** |
||
38 | * {@inheritdoc} |
||
39 | */ |
||
40 | public function has($key) |
||
41 | { |
||
42 | if (!array_key_exists($key, $this->items)) { |
||
43 | return false; |
||
44 | } |
||
45 | |||
46 | if ($this->hasExpired($key)) { |
||
47 | return (bool) $this->delete($key); |
||
48 | } |
||
49 | |||
50 | return true; |
||
51 | } |
||
52 | |||
53 | /** |
||
54 | * {@inheritdoc} |
||
55 | */ |
||
56 | public function get($key, $default = null) |
||
57 | { |
||
58 | try { |
||
59 | return $this->demand($key); |
||
60 | } catch (CacheException $exception) { |
||
61 | return $default; |
||
62 | } |
||
63 | } |
||
64 | |||
65 | /** |
||
66 | * {@inheritdoc} |
||
67 | */ |
||
68 | public function demand($key) |
||
69 | { |
||
70 | if (!array_key_exists($key, $this->items)) { |
||
71 | throw new NotFoundException($key); |
||
72 | } |
||
73 | |||
74 | if ($this->hasExpired($key)) { |
||
75 | $this->delete($key); |
||
76 | throw new ExpiredException($key); |
||
77 | } |
||
78 | |||
79 | return true; |
||
80 | } |
||
81 | |||
82 | /** |
||
83 | * {@inheritdoc} |
||
84 | */ |
||
85 | public function delete($key) |
||
86 | { |
||
87 | if (array_key_exists($key, $this->items)) { |
||
88 | unset($this->items[$key]); |
||
89 | } |
||
90 | } |
||
91 | |||
92 | /** |
||
93 | * {@inheritdoc} |
||
94 | */ |
||
95 | public function flush() |
||
99 | |||
100 | /** |
||
101 | * Checks whether an item as expired |
||
102 | * |
||
103 | * @param string $key |
||
104 | * |
||
105 | * @return bool |
||
106 | */ |
||
107 | private function hasExpired($key) |
||
111 | } |
||
112 |