Passed
Push — main ( 29b1f6...a8c6a0 )
by Sílvio
01:02 queued 16s
created

ArrayCacheStore::getMany()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 3
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Silviooosilva\CacheerPhp\CacheStore;
4
5
use Silviooosilva\CacheerPhp\Utils\CacheLogger;
6
use Silviooosilva\CacheerPhp\Interface\CacheerInterface;
7
8
/**
9
 * Class ArrayCacheStore
10
 * @author Sílvio Silva <https://github.com/silviooosilva>
11
 * @package Silviooosilva\CacheerPhp
12
 */
13
class ArrayCacheStore implements CacheerInterface
14
{
15
16
  /**
17
  * @param array $arrayStore
18
  */
19
  private array $arrayStore = [];
20
21
  /**
22
   * @param boolean
23
   */
24
  private bool $success = false;
25
26
  /**
27
   * @param string
28
   */
29
  private string $message = '';
30
31
  /**
32
   * @var CacheLogger
33
   */
34
  private $logger = null;
35
36
  public function __construct(string $logPath)
37
  {
38
    $this->logger = new CacheLogger($logPath);
39
  }
40
41
  /**
42
   * @param string $cacheKey
43
   * @param mixed  $cacheData
44
   * @param string $namespace
45
   * @return bool
46
   */
47
  public function appendCache(string $cacheKey, mixed $cacheData, string $namespace = '')
48
  {
49
      $arrayStoreKey = $this->buildArrayKey($cacheKey, $namespace);
50
51
      if (!$this->has($cacheKey, $namespace)) {
52
          $this->setMessage("cacheData can't be appended, because doesn't exist or expired", false);
53
          $this->logger->debug("{$this->getMessage()} from array driver.");
54
          return false;
55
      }
56
57
      $this->arrayStore[$arrayStoreKey]['cacheData'] = serialize($cacheData);
58
      $this->setMessage("Cache appended successfully", true);
59
      return true;
60
  }
61
62
  /**
63
   * @param string $cacheKey
64
   * @param string $namespace
65
   * @return string
66
   */
67
  private function buildArrayKey(string $cacheKey, string $namespace = '')
68
  {
69
    return !empty($namespace) ? ($namespace . ':' . $cacheKey) : $cacheKey;
70
  }
71
72
  /**
73
   * @param string $cacheKey
74
   * @param string $namespace
75
   * @return void
76
   */
77
  public function clearCache(string $cacheKey, string $namespace = '')
78
  {
79
    $arrayStoreKey = $this->buildArrayKey($cacheKey, $namespace);
80
    unset($this->arrayStore[$arrayStoreKey]);
81
    $this->setMessage("Cache cleared successfully", true);
82
    $this->logger->debug("{$this->getMessage()} from array driver.");
83
  }
84
85
  /**
86
   * @param string $cacheKey
87
   * @param int $amount
88
   * @param string $namespace
89
   * @return bool
90
   */
91
  public function decrement(string $cacheKey, int $amount = 1, string $namespace = '')
92
  {
93
    return $this->increment($cacheKey, ($amount * -1), $namespace);
94
  }
95
96
  /**
97
   * @return void
98
   */
99
  public function flushCache()
100
  {
101
    unset($this->arrayStore);
102
    $this->arrayStore = [];
103
    $this->setMessage("Cache flushed successfully", true);
104
    $this->logger->debug("{$this->getMessage()} from array driver.");
105
  }
106
107
  /**
108
   * @param string $cacheKey
109
   * @param mixed $cacheData
110
   * @param string $namespace
111
   * @param int|string $ttl
112
   * @return void
113
   */
114
  public function forever(string $cacheKey, mixed $cacheData)
115
  {
116
    $this->putCache($cacheKey, $cacheData, ttl: 31536000 * 1000);
117
    $this->setMessage($this->getMessage(), $this->isSuccess());
118
  }
119
120
  /**
121
   * @param string $cacheKey
122
   * @param string $namespace
123
   * @param int|string $ttl
124
   * @return mixed
125
   */
126
  public function getCache(string $cacheKey, string $namespace = '', string|int $ttl = 3600)
127
  {
128
    $arrayStoreKey = $this->buildArrayKey($cacheKey, $namespace);
129
130
    if (!$this->has($cacheKey, $namespace)) {
131
      $this->setMessage("cacheData not found, does not exists or expired", false);
132
      $this->logger->debug("{$this->getMessage()} from array driver.");
133
      return false;
134
    }
135
136
    $cacheData = $this->arrayStore[$arrayStoreKey];
137
    $expirationTime = $cacheData['expirationTime'] ?? 0;
138
    $now = time();
139
140
    if($expirationTime !== 0 && $now >= $expirationTime) {
141
      list($np, $key) = explode(':', $arrayStoreKey);
142
      $this->clearCache($key, $np);
143
      $this->setMessage("cacheKey: {$key} has expired.", false);
144
      $this->logger->debug("{$this->getMessage()} from array driver.");
145
      return false;
146
    }
147
148
    $this->setMessage("Cache retrieved successfully", true);
149
    $this->logger->debug("{$this->getMessage()} from array driver.");
150
    return $this->serialize($cacheData['cacheData'], false);
151
  }
152
153
  /**
154
   * @param array $cacheKeys
155
   * @param string $namespace
156
   * @param string|int $ttl
157
   * @return array
158
   */
159
  public function getMany(array $cacheKeys, string $namespace = '', string|int $ttl = 3600)
160
  {
161
    $results = [];
162
    foreach ($cacheKeys as $cacheKey) {
163
      $results[$cacheKey] = $this->getCache($cacheKey, $namespace, $ttl);
164
    }
165
    return $results;
166
  }
167
168
  /**
169
   * @param string $cacheKey
170
   * @param string $namespace
171
   * @return bool
172
   */
173
  public function has(string $cacheKey, string $namespace = '')
174
  {
175
    $arrayStoreKey = $this->buildArrayKey($cacheKey, $namespace);
176
    return isset($this->arrayStore[$arrayStoreKey]) && time() < $this->arrayStore[$arrayStoreKey]['expirationTime'];
177
  }
178
179
  /**
180
   * @param string $cacheKey
181
   * @param int $amount
182
   * @param string $namespace
183
   * @return bool
184
   */
185
  public function increment(string $cacheKey, int $amount = 1, string $namespace = '')
186
  {
187
    $cacheData = $this->getCache($cacheKey, $namespace);
188
189
    if(!empty($cacheData) && is_numeric($cacheData)) {
190
      $this->putCache($cacheKey, (int)($cacheData + $amount), $namespace);
191
      $this->setMessage($this->getMessage(), $this->isSuccess());
192
      return true;
193
    }
194
195
    return false;
196
  }
197
198
  /**
199
   * @return boolean
200
   */
201
  public function isSuccess()
202
  {
203
    return $this->success;
204
  }
205
206
  /**
207
   * @return string
208
   */
209
  public function getMessage()
210
  {
211
    return $this->message;
212
  }
213
214
  /**
215
   * @param string $cacheKey
216
   * @param mixed $cacheData
217
   * @param string $namespace
218
   * @param int|string $ttl
219
   * @return bool
220
   */
221
  public function putCache(string $cacheKey, mixed $cacheData, string $namespace = '', int|string $ttl = 3600)
222
  {
223
    $arrayStoreKey = $this->buildArrayKey($cacheKey, $namespace);
224
225
    $this->arrayStore[$arrayStoreKey] = [
226
      'cacheData' => serialize($cacheData),
227
      'expirationTime' => time() + $ttl
228
    ];
229
230
    $this->setMessage("Cache stored successfully", true);
231
    $this->logger->debug("{$this->getMessage()} from Array driver.");
232
    return true;
233
  }
234
235
  /**
236
   * @param array $items
237
   * @param string $namespace
238
   * @param int $batchSize
239
   * @return void
240
   */
241
  public function putMany(array $items, string $namespace = '', int $batchSize = 100)
242
  {
243
    $chunks = array_chunk($items, $batchSize, true);
244
245
    foreach ($chunks as $chunk) {
246
      foreach ($chunk as $key => $data) {
247
          $this->putCache($data['cacheKey'], $data['cacheData'], $namespace);
248
        }
249
      }
250
    $this->setMessage("{$this->getMessage()}", $this->isSuccess());
251
    $this->logger->debug("{$this->getMessage()} from Array driver.");
252
  }
253
254
  /**
255
   * @param string $cacheKey
256
   * @param string|int $ttl
257
   * @param string $namespace
258
   * @return void
259
   */
260
  public function renewCache(string $cacheKey, int|string $ttl = 3600, string $namespace = '')
261
  {
262
    $arrayStoreKey = $this->buildArrayKey($cacheKey, $namespace);
263
264
    if (isset($this->arrayStore[$arrayStoreKey])) {
265
        $ttlSeconds = is_numeric($ttl) ? (int) $ttl : strtotime($ttl) - time();
266
        $this->arrayStore[$arrayStoreKey]['expirationTime'] = time() + $ttlSeconds;
267
        $this->setMessage("cacheKey: {$cacheKey} renewed successfully", true);
268
        $this->logger->debug("{$this->getMessage()} from array driver.");
269
      }
270
  }
271
272
  /**
273
   * @param string  $message
274
   * @param boolean $success
275
   * @return void
276
   */
277
  private function setMessage(string $message, bool $success)
278
  {
279
    $this->message = $message;
280
    $this->success = $success;
281
  }
282
283
  /**
284
   * @param mixed $data
285
   * @param bool $serialize
286
   * @return mixed
287
   */
288
  private function serialize(mixed $data, bool $serialize = true)
289
  {
290
    return $serialize ? serialize($data) : unserialize($data);
291
  }
292
}
293