DatabaseCacheStore::updateCache()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 2
eloc 6
c 2
b 0
f 1
nc 2
nop 3
dl 0
loc 9
rs 10
1
<?php
2
3
namespace Silviooosilva\CacheerPhp\CacheStore;
4
5
use Silviooosilva\CacheerPhp\Interface\CacheerInterface;
6
use Silviooosilva\CacheerPhp\Helpers\CacheDatabaseHelper;
7
use Silviooosilva\CacheerPhp\Utils\CacheLogger;
8
use Silviooosilva\CacheerPhp\Repositories\CacheDatabaseRepository;
9
10
/**
11
 * Class DatabaseCacheStore
12
 * @author Sílvio Silva <https://github.com/silviooosilva>
13
 * @package Silviooosilva\CacheerPhp
14
 */
15
class DatabaseCacheStore implements CacheerInterface
16
{
17
    /**
18
     * @param boolean
19
     */
20
    private bool $success = false;
21
22
    /**
23
     * @param string
24
     */
25
    private string $message = '';
26
27
    /**
28
     * @var CacheLogger
29
     */
30
    private $logger = null;
31
32
    /**
33
     * @var CacheDatabaseRepository
34
     */
35
    private $cacheRepository;
36
37
    /**
38
     * DatabaseCacheStore constructor.
39
     *
40
     * @param string $logPath
41
     */
42
    public function __construct(string $logPath)
43
    {
44
        $this->logger = new CacheLogger($logPath);
45
        $this->cacheRepository = new CacheDatabaseRepository();
46
    }
47
48
    /**
49
     * Appends data to an existing cache item.
50
     * 
51
     * @param string $cacheKey
52
     * @param mixed  $cacheData
53
     * @param string $namespace
54
     * @return bool
55
     */
56
    public function appendCache(string $cacheKey, mixed $cacheData, string $namespace = '')
57
    {
58
        $currentCacheData = $this->getCache($cacheKey, $namespace);
59
        $mergedCacheData = CacheDatabaseHelper::arrayIdentifier($currentCacheData, $cacheData);
60
61
        if ($this->updateCache($cacheKey, $mergedCacheData, $namespace)) {
62
            $this->logger->debug("{$this->getMessage()} from database driver.");
63
            return true;
64
        }
65
66
        $this->logger->error("{$this->getMessage()} from database driver.");
67
        return false;
68
    }
69
70
    /**
71
     * Clears a specific cache item.
72
     * 
73
     * @param string $cacheKey
74
     * @param string $namespace
75
     * @return void
76
     */
77
    public function clearCache(string $cacheKey, string $namespace = '')
78
    {
79
        $data = $this->cacheRepository->clear($cacheKey, $namespace);
80
        if($data) {
81
            $this->setMessage("Cache deleted successfully!", true);
82
        } else {
83
            $this->setMessage("Cache does not exists!", false);
84
        }
85
86
        $this->logger->debug("{$this->getMessage()} from database driver.");
87
    }
88
89
    /**
90
     * Flushes all cache items.
91
     * 
92
     * @return void
93
     */
94
    public function flushCache()
95
    {
96
        if($this->cacheRepository->flush()){
97
            $this->setMessage("Flush finished successfully", true);
98
        } else {
99
            $this->setMessage("Something went wrong. Please, try again.", false);
100
        }
101
102
        $this->logger->info("{$this->getMessage()} from database driver.");
103
104
    }
105
106
    /**
107
     * Gets a single cache item.
108
     * 
109
     * @param string $cacheKey
110
     * @param string $namespace
111
     * @param string|int $ttl
112
     * @return mixed
113
     */
114
    public function getCache(string $cacheKey, string $namespace = '', string|int $ttl = 3600)
115
    {
116
        $cacheData = $this->retrieveCache($cacheKey, $namespace);
117
        if ($cacheData) {
118
            $this->setMessage("Cache retrieved successfully", true);
119
            $this->logger->debug("{$this->getMessage()} from database driver.");
120
            return $cacheData;
121
        }
122
        $this->setMessage("CacheData not found, does not exists or expired", false);
123
        $this->logger->info("{$this->getMessage()} from database driver.");
124
        return null;
125
    }
126
127
    /**
128
     * Gets all items in a specific namespace.
129
     * 
130
     * @param string $namespace
131
     * @return array
132
     */
133
    public function getAll(string $namespace = '')
134
    {
135
        $cacheData = $this->cacheRepository->getAll($namespace);
136
        if ($cacheData) {
137
            $this->setMessage("Cache retrieved successfully", true);
138
            $this->logger->debug("{$this->getMessage()} from database driver.");
139
            return $cacheData;
140
        }
141
        $this->setMessage("No cache data found for the provided namespace", false);
142
        $this->logger->info("{$this->getMessage()} from database driver.");
143
        return [];
144
    }
145
146
    /**
147
     * Retrieves multiple cache items by their keys.
148
     * 
149
     * @param array  $cacheKeys
150
     * @param string $namespace
151
     * @param string|int $ttl
152
     * @return array
153
     */
154
    public function getMany(array $cacheKeys, string $namespace = '', string|int $ttl = 3600)
155
    {
156
        $cacheData = [];
157
        foreach ($cacheKeys as $cacheKey) {
158
            $data = $this->getCache($cacheKey, $namespace, $ttl);
159
            if ($data) {
160
                $cacheData[$cacheKey] = $data;
161
            }
162
        }
163
        if (!empty($cacheData)) {
164
            $this->setMessage("Cache retrieved successfully", true);
165
            $this->logger->debug("{$this->getMessage()} from database driver.");
166
            return $cacheData;
167
        }
168
        $this->setMessage("No cache data found for the provided keys", false);
169
        $this->logger->info("{$this->getMessage()} from database driver.");
170
        return [];
171
    }
172
173
    /**
174
     * Checks if a cache item exists.
175
     * 
176
     * @return string
177
     */
178
    public function getMessage()
179
    {
180
        return $this->message;
181
    }
182
183
    /**
184
     * Checks if a cache item exists.
185
     * 
186
     * @param string $cacheKey
187
     * @param string $namespace
188
     * @return void
189
     */
190
    public function has(string $cacheKey, string $namespace = '')
191
    {
192
        $cacheData = $this->getCache($cacheKey, $namespace);
193
        if ($cacheData) {
194
            $this->logger->debug("Cache key: {$cacheKey} exists and it's available from database driver.");
195
        }
196
        $this->logger->warning("{$this->getMessage()} from database driver.");
197
    }
198
199
    /**
200
     * Checks if the last operation was successful.
201
     * 
202
     * @return boolean
203
     */
204
    public function isSuccess()
205
    {
206
        return $this->success;
207
    }
208
209
    /**
210
     * Store multiple items in the cache.
211
     * 
212
     * @param array   $items
213
     * @param string  $namespace
214
     * @param integer $batchSize
215
     * @return void
216
     */
217
    public function putMany(array $items, string $namespace = '', int $batchSize = 100)
218
    {
219
        $processedCount = 0;
220
        $itemCount = count($items);
221
        while ($processedCount < $itemCount) {
222
            $batchItems = array_slice($items, $processedCount, $batchSize);
223
            $this->processBatchItems($batchItems, $namespace);
224
            $processedCount += count($batchItems);
225
        }
226
    }
227
228
    /**
229
     * Stores an item in the cache with a specific TTL.
230
     * 
231
     * @param string $cacheKey
232
     * @param mixed  $cacheData
233
     * @param string $namespace
234
     * @param string|int $ttl
235
     * @return bool
236
     */
237
    public function putCache(string $cacheKey, mixed $cacheData, string $namespace = '', string|int $ttl = 3600)
238
    {
239
        if($this->storeCache($cacheKey, $cacheData, $namespace, $ttl)){
240
            $this->logger->debug("{$this->getMessage()} from database driver.");
241
            return true;
242
        }
243
        $this->logger->error("{$this->getMessage()} from database driver.");
244
        return false;
245
    }
246
247
    /**
248
     * Renews the cache for a specific key with a new TTL.
249
     * 
250
     * @param string $cacheKey
251
     * @param string|int $ttl
252
     * @param string $namespace
253
     * @return void
254
     */
255
    public function renewCache(string $cacheKey, int | string $ttl, string $namespace = '')
256
    {
257
        $cacheData = $this->getCache($cacheKey, $namespace);
258
        if ($cacheData) {
259
            $this->renew($cacheKey, $ttl, $namespace);
260
            $this->setMessage("Cache with key {$cacheKey} renewed successfully", true);
261
            $this->logger->debug("{$this->getMessage()} from database driver.");
262
        }
263
    }
264
265
    /**
266
     * Processes a batch of cache items.
267
     * 
268
     * @param array  $batchItems
269
     * @param string $namespace
270
     * @return void
271
     */
272
    private function processBatchItems(array $batchItems, string $namespace)
273
    {
274
        foreach($batchItems as $item) {
275
            CacheDatabaseHelper::validateCacheItem($item);
276
            $cacheKey = $item['cacheKey'];
277
            $cacheData = $item['cacheData'];
278
            $mergedData = CacheDatabaseHelper::mergeCacheData($cacheData);
279
            $this->putCache($cacheKey, $mergedData, $namespace);
280
        }
281
    }
282
283
    /**
284
     * Renews the expiration time of a cache item.
285
     * 
286
     * @param string $cacheKey
287
     * @param string|int $ttl
288
     * @param string $namespace
289
     * @return bool
290
     */
291
    private function renew(string $cacheKey, string|int $ttl = 3600, string $namespace = '')
292
    {
293
        $cacheData = $this->getCache($cacheKey, $namespace);
294
        if ($cacheData) {
295
            $renewedCache = $this->cacheRepository->renew($cacheKey, $ttl, $namespace);
296
            if ($renewedCache) {
297
                $this->setMessage("Cache with key {$cacheKey} renewed successfully", true);
298
                $this->logger->debug("{$this->getMessage()} from database driver.");
299
                return true;
300
            }
301
            return false;
302
        }
303
        return false;
304
    }
305
306
    /**
307
     * Sets a message and its success status.
308
     * 
309
     * @param string  $message
310
     * @param boolean $success
311
     * @return void
312
     */
313
    private function setMessage(string $message, bool $success)
314
    {
315
        $this->message = $message;
316
        $this->success = $success;
317
    }
318
319
    /**
320
     * Retrieves a cache item by its key.
321
     * @param string $cacheKey
322
     * @param string $namespace
323
     * @return mixed
324
     */
325
    private function retrieveCache(string $cacheKey, string $namespace = '')
326
    {
327
        return $this->cacheRepository->retrieve($cacheKey, $namespace);
328
    }
329
330
    /**
331
     * Stores a cache item.
332
     * 
333
     * @param string $cacheKey
334
     * @param mixed  $cacheData
335
     * @param string $namespace
336
     * @param integer $ttl
337
     * @return bool
338
     */
339
    private function storeCache(string $cacheKey, mixed $cacheData, string $namespace = '', string|int $ttl = 3600)
340
    {
341
        $data = $this->cacheRepository->store($cacheKey, $cacheData, $namespace, $ttl);
342
        if($data) {
343
            $this->setMessage("Cache Stored Successfully", true);
344
            return true;
345
        }
346
        $this->setMessage("Already exists a cache with this key...", false);
347
        return false;
348
    }
349
350
    /**
351
     * Updates an existing cache item.
352
     * 
353
     * @param string $cacheKey
354
     * @param mixed  $cacheData
355
     * @param string $namespace
356
     * @return bool
357
     */
358
    private function updateCache(string $cacheKey, mixed $cacheData, string $namespace = '')
359
    {
360
        $data = $this->cacheRepository->update($cacheKey, $cacheData, $namespace);
361
        if($data) {
362
            $this->setMessage("Cache updated successfully.", true);
363
            return true;
364
        }
365
        $this->setMessage("Cache does not exist or update failed!", false);
366
        return false;
367
    }
368
}
369