blob: d7480a7b540e105374bd8defe5322ed0cc19de7c [file] [log] [blame]
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +02001<?php
2
3namespace LdapRecord\Query;
4
5use Psr\SimpleCache\CacheInterface;
6
7class ArrayCacheStore implements CacheInterface
8{
9 use InteractsWithTime;
10
11 /**
12 * An array of stored values.
13 *
14 * @var array
15 */
16 protected $storage = [];
17
18 /**
19 * @inheritdoc
20 */
21 public function get($key, $default = null)
22 {
23 if (! isset($this->storage[$key])) {
24 return $default;
25 }
26
27 $item = $this->storage[$key];
28
29 $expiresAt = $item['expiresAt'] ?? 0;
30
31 if ($expiresAt !== 0 && $this->currentTime() > $expiresAt) {
32 $this->delete($key);
33
34 return $default;
35 }
36
37 return $item['value'];
38 }
39
40 /**
41 * @inheritdoc
42 */
43 public function set($key, $value, $ttl = null)
44 {
45 $this->storage[$key] = [
46 'value' => $value,
47 'expiresAt' => $this->calculateExpiration($ttl),
48 ];
49
50 return true;
51 }
52
53 /**
54 * Get the expiration time of the key.
55 *
56 * @param int $seconds
57 *
58 * @return int
59 */
60 protected function calculateExpiration($seconds)
61 {
62 return $this->toTimestamp($seconds);
63 }
64
65 /**
66 * Get the UNIX timestamp for the given number of seconds.
67 *
68 * @param int $seconds
69 *
70 * @return int
71 */
72 protected function toTimestamp($seconds)
73 {
74 return $seconds > 0 ? $this->availableAt($seconds) : 0;
75 }
76
77 /**
78 * @inheritdoc
79 */
80 public function delete($key)
81 {
82 unset($this->storage[$key]);
83
84 return true;
85 }
86
87 /**
88 * @inheritdoc
89 */
90 public function clear()
91 {
92 $this->storage = [];
93
94 return true;
95 }
96
97 /**
98 * @inheritdoc
99 */
100 public function getMultiple($keys, $default = null)
101 {
102 $values = [];
103
104 foreach ($keys as $key) {
105 $values[$key] = $this->get($key, $default);
106 }
107
108 return $values;
109 }
110
111 /**
112 * @inheritdoc
113 */
114 public function setMultiple($values, $ttl = null)
115 {
116 foreach ($values as $key => $value) {
117 $this->set($key, $value, $ttl);
118 }
119
120 return true;
121 }
122
123 /**
124 * @inheritdoc
125 */
126 public function deleteMultiple($keys)
127 {
128 foreach ($keys as $key) {
129 $this->delete($key);
130 }
131
132 return true;
133 }
134
135 /**
136 * @inheritdoc
137 */
138 public function has($key)
139 {
140 return isset($this->storage[$key]);
141 }
142}