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

DatabaseCacheStore   A

Complexity

Total Complexity 34

Size/Duplication

Total Lines 295
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
eloc 97
dl 0
loc 295
rs 9.68
c 2
b 0
f 1
wmc 34

18 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getCache() 0 11 2
A flushCache() 0 9 2
A appendCache() 0 12 2
A clearCache() 0 10 2
A isSuccess() 0 3 1
A retrieveCache() 0 3 1
A updateCache() 0 9 2
A processBatchItems() 0 8 2
A getMany() 0 17 4
A has() 0 7 2
A getMessage() 0 3 1
A renewCache() 0 7 2
A storeCache() 0 9 2
A setMessage() 0 4 1
A renew() 0 13 3
A putMany() 0 8 2
A putCache() 0 8 2
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
    public function __construct(string $logPath)
38
    {
39
        $this->logger = new CacheLogger($logPath);
40
        $this->cacheRepository = new CacheDatabaseRepository();
41
    }
42
43
    /**
44
     * @param string $cacheKey
45
     * @param mixed  $cacheData
46
     * @param string $namespace
47
     * @return bool
48
     */
49
    public function appendCache(string $cacheKey, mixed $cacheData, string $namespace = '')
50
    {
51
        $currentCacheData = $this->getCache($cacheKey, $namespace);
52
        $mergedCacheData = CacheDatabaseHelper::arrayIdentifier($currentCacheData, $cacheData);
53
54
        if ($this->updateCache($cacheKey, $mergedCacheData, $namespace)) {
55
            $this->logger->debug("{$this->getMessage()} from database driver.");
56
            return true;
57
        }
58
59
        $this->logger->error("{$this->getMessage()} from database driver.");
60
        return false;
61
    }
62
63
    /**
64
     * @param string $cacheKey
65
     * @param string $namespace
66
     * @return void
67
     */
68
    public function clearCache(string $cacheKey, string $namespace = '')
69
    {
70
        $data = $this->cacheRepository->clear($cacheKey, $namespace);
71
        if($data) {
72
            $this->setMessage("Cache deleted successfully!", true);
73
        } else {
74
            $this->setMessage("Cache does not exists!", false);
75
        }
76
77
        $this->logger->debug("{$this->getMessage()} from database driver.");
78
    }
79
80
    /**
81
     * @return void
82
     */
83
    public function flushCache()
84
    {
85
        if($this->cacheRepository->flush()){
86
            $this->setMessage("Flush finished successfully", true);
87
        } else {
88
            $this->setMessage("Something went wrong. Please, try again.", false);
89
        }
90
91
        $this->logger->info("{$this->getMessage()} from database driver.");
92
93
    }
94
95
    /**
96
     * @param string $cacheKey
97
     * @param string $namespace
98
     * @param string|int $ttl
99
     * @return mixed
100
     */
101
    public function getCache(string $cacheKey, string $namespace = '', string|int $ttl = 3600)
102
    {
103
        $cacheData = $this->retrieveCache($cacheKey, $namespace);
104
        if ($cacheData) {
105
            $this->setMessage("Cache retrieved successfully", true);
106
            $this->logger->debug("{$this->getMessage()} from database driver.");
107
            return $cacheData;
108
        }
109
        $this->setMessage("CacheData not found, does not exists or expired", false);
110
        $this->logger->info("{$this->getMessage()} from database driver.");
111
        return null;
112
    }
113
114
    /**
115
     * @param array  $cacheKeys
116
     * @param string $namespace
117
     * @param string|int $ttl
118
     * @return array
119
     */
120
    public function getMany(array $cacheKeys, string $namespace = '', string|int $ttl = 3600)
121
    {
122
        $cacheData = [];
123
        foreach ($cacheKeys as $cacheKey) {
124
            $data = $this->getCache($cacheKey, $namespace, $ttl);
125
            if ($data) {
126
                $cacheData[$cacheKey] = $data;
127
            }
128
        }
129
        if (!empty($cacheData)) {
130
            $this->setMessage("Cache retrieved successfully", true);
131
            $this->logger->debug("{$this->getMessage()} from database driver.");
132
            return $cacheData;
133
        }
134
        $this->setMessage("No cache data found for the provided keys", false);
135
        $this->logger->info("{$this->getMessage()} from database driver.");
136
        return [];
137
    }
138
139
    /**
140
     * @return string
141
     */
142
    public function getMessage()
143
    {
144
        return $this->message;
145
    }
146
147
    /**
148
     * @param string $cacheKey
149
     * @param string $namespace
150
     * @return void
151
     */
152
    public function has(string $cacheKey, string $namespace = '')
153
    {
154
        $cacheData = $this->getCache($cacheKey, $namespace);
155
        if ($cacheData) {
156
            $this->logger->debug("Cache key: {$cacheKey} exists and it's available from database driver.");
157
        }
158
        $this->logger->warning("{$this->getMessage()} from database driver.");
159
    }
160
161
    /**
162
     * @return boolean
163
     */
164
    public function isSuccess()
165
    {
166
        return $this->success;
167
    }
168
169
    /**
170
     * @param array   $items
171
     * @param string  $namespace
172
     * @param integer $batchSize
173
     * @return void
174
     */
175
    public function putMany(array $items, string $namespace = '', int $batchSize = 100)
176
    {
177
        $processedCount = 0;
178
        $itemCount = count($items);
179
        while ($processedCount < $itemCount) {
180
            $batchItems = array_slice($items, $processedCount, $batchSize);
181
            $this->processBatchItems($batchItems, $namespace);
182
            $processedCount += count($batchItems);
183
        }
184
    }
185
186
    /**
187
     * @param string $cacheKey
188
     * @param mixed  $cacheData
189
     * @param string $namespace
190
     * @param string|int $ttl
191
     * @return bool
192
     */
193
    public function putCache(string $cacheKey, mixed $cacheData, string $namespace = '', string|int $ttl = 3600)
194
    {
195
        if($this->storeCache($cacheKey, $cacheData, $namespace, $ttl)){
196
            $this->logger->debug("{$this->getMessage()} from database driver.");
197
            return true;
198
        }
199
        $this->logger->error("{$this->getMessage()} from database driver.");
200
        return false;
201
    }
202
203
    /**
204
     * @param string $cacheKey
205
     * @param string|int $ttl
206
     * @param string $namespace
207
     * @return void
208
     */
209
    public function renewCache(string $cacheKey, int | string $ttl, string $namespace = '')
210
    {
211
        $cacheData = $this->getCache($cacheKey, $namespace);
212
        if ($cacheData) {
213
            $this->renew($cacheKey, $ttl, $namespace);
214
            $this->setMessage("Cache with key {$cacheKey} renewed successfully", true);
215
            $this->logger->debug("{$this->getMessage()} from database driver.");
216
        }
217
    }
218
219
    /**
220
     * @param array  $batchItems
221
     * @param string $namespace
222
     * @return void
223
     */
224
    private function processBatchItems(array $batchItems, string $namespace)
225
    {
226
        foreach($batchItems as $item) {
227
            CacheDatabaseHelper::validateCacheItem($item);
228
            $cacheKey = $item['cacheKey'];
229
            $cacheData = $item['cacheData'];
230
            $mergedData = CacheDatabaseHelper::mergeCacheData($cacheData);
231
            $this->putCache($cacheKey, $mergedData, $namespace);
232
        }
233
    }
234
235
    /**
236
     * @param string $cacheKey
237
     * @param string|int $ttl
238
     * @param string $namespace
239
     * @return bool
240
     */
241
    private function renew(string $cacheKey, string|int $ttl = 3600, string $namespace = '')
242
    {
243
        $cacheData = $this->getCache($cacheKey, $namespace);
244
        if ($cacheData) {
245
            $renewedCache = $this->cacheRepository->renew($cacheKey, $ttl, $namespace);
246
            if ($renewedCache) {
247
                $this->setMessage("Cache with key {$cacheKey} renewed successfully", true);
248
                $this->logger->debug("{$this->getMessage()} from database driver.");
249
                return true;
250
            }
251
            return false;
252
        }
253
        return false;
254
    }
255
256
    /**
257
     * @param string  $message
258
     * @param boolean $success
259
     * @return void
260
     */
261
    private function setMessage(string $message, bool $success)
262
    {
263
        $this->message = $message;
264
        $this->success = $success;
265
    }
266
267
    /**
268
     * @param string $cacheKey
269
     * @param string $namespace
270
     * @return mixed
271
     */
272
    private function retrieveCache(string $cacheKey, string $namespace = '')
273
    {
274
        return $this->cacheRepository->retrieve($cacheKey, $namespace);
275
    }
276
277
    /**
278
     * @param string $cacheKey
279
     * @param mixed  $cacheData
280
     * @param string $namespace
281
     * @param integer $ttl
282
     * @return bool
283
     */
284
    private function storeCache(string $cacheKey, mixed $cacheData, string $namespace = '', string|int $ttl = 3600)
285
    {
286
        $data = $this->cacheRepository->store($cacheKey, $cacheData, $namespace, $ttl);
287
        if($data) {
288
            $this->setMessage("Cache Stored Successfully", true);
289
            return true;
290
        }
291
        $this->setMessage("Already exists a cache with this key...", false);
292
        return false;
293
    }
294
295
    /**
296
     * @param string $cacheKey
297
     * @param mixed  $cacheData
298
     * @param string $namespace
299
     * @return bool
300
     */
301
    private function updateCache(string $cacheKey, mixed $cacheData, string $namespace = '')
302
    {
303
        $data = $this->cacheRepository->update($cacheKey, $cacheData, $namespace);
304
        if($data) {
305
            $this->setMessage("Cache updated successfully.", true);
306
            return true;
307
        }
308
        $this->setMessage("Cache does not exist or update failed!", false);
309
        return false;
310
    }
311
}
312