Passed
Push — develop ( 3d2eea...96fcf0 )
by
unknown
07:38
created

ZanzaraCache::deleteCacheGlobalData()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Zanzara;
4
5
use React\Cache\CacheInterface;
6
use React\Promise\PromiseInterface;
7
8
/**
9
 * @method get($key, $default = null)
10
 * @method set($key, $value, $ttl = null)
11
 * @method delete($key)
12
 * @method setMultiple(array $values, $ttl = null)
13
 * @method deleteMultiple(array $keys)
14
 * @method clear()
15
 * @method has($key)
16
 */
17
class ZanzaraCache
18
{
19
    /**
20
     * @var CacheInterface|null
21
     */
22
    private $cache;
23
24
    /**
25
     * @var ZanzaraLogger
26
     */
27
    private $logger;
28
29
    private const CONVERSATION = "CONVERSATION";
30
31
    private const CHATDATA = " CHATDATA";
32
33
    private const USERDATA = "USERDATA";
34
35
    private const GLOBALDATA = "GLOBALDATA";
36
37
    /**
38
     * ZanzaraLogger constructor.
39
     * @param CacheInterface|null $cache
40
     * @param ZanzaraLogger $logger
41
     */
42
    public function __construct(?CacheInterface $cache, ZanzaraLogger $logger)
43
    {
44
        $this->logger = $logger;
45
        $this->cache = $cache;
46
    }
47
48
49
    public function getGlobalCacheData()
50
    {
51
        $cacheKey = self::GLOBALDATA;
52
        return $this->getCache($cacheKey);
53
    }
54
55
    public function setGlobalCacheData($key, $data)
56
    {
57
        $cacheKey = self::GLOBALDATA;
58
        return $this->setCache($cacheKey, $key, $data);
59
    }
60
61
    public function getCacheItemGlobalData($key)
62
    {
63
        $cacheKey = self::GLOBALDATA;
64
        return $this->getCacheItem($cacheKey, $key);
65
    }
66
67
    public function deleteCacheGlobalData()
68
    {
69
        $cacheKey = self::GLOBALDATA;
70
        return $this->deleteCache([$cacheKey]);
71
    }
72
73
    public function deleteCacheItemGlobalData($key)
74
    {
75
        $cacheKey = self::GLOBALDATA;
76
        return $this->deleteCacheItem($cacheKey, $key);
77
    }
78
79
80
    /**
81
     * Get the correct key value for chatId data stored in cache
82
     * @param $chatId
83
     * @return string
84
     */
85
    private function getKeyChatId($chatId)
86
    {
87
        return ZanzaraCache::CHATDATA . strval($chatId);
88
    }
89
90
    public function getCacheChatData($chatId)
91
    {
92
        $cacheKey = $this->getKeyChatId($chatId);
93
        return $this->getCache($cacheKey);
94
    }
95
96
    public function getItemCacheChatData($chatId, $key)
97
    {
98
        $cacheKey = $this->getKeyChatId($chatId);
99
        return $this->getCacheItem($cacheKey, $key);
100
    }
101
102
    public function setCacheChatData($chatId, $key, $data)
103
    {
104
        $cacheKey = $this->getKeyChatId($chatId);
105
        return $this->setCache($cacheKey, $key, $data);
106
    }
107
108
    public function deleteAllCacheChatData($chatId)
109
    {
110
        $cacheKey = $this->getKeyChatId($chatId);
111
        return $this->deleteCache([$cacheKey]);
112
    }
113
114
    public function deleteCacheItemChatData($chatId, $key)
115
    {
116
        $cacheKey = $this->getKeyChatId($chatId);
117
        return $this->deleteCacheItem($cacheKey, $key);
118
119
    }
120
121
122
    /**
123
     * Get the correct key value for userId data stored in cache
124
     * @param $userId
125
     * @return string
126
     */
127
    private function getKeyUserId($userId)
128
    {
129
        return ZanzaraCache::USERDATA . strval($userId);
130
    }
131
132
    public function getCacheUserData($userId)
133
    {
134
        $cacheKey = $this->getKeyUserId($userId);
135
        return $this->getCache($cacheKey);
136
    }
137
138
    public function getItemCacheUserData($userId, $key){
139
        $cacheKey = $this->getKeyUserId($userId);
140
        return $this->getCacheItem($cacheKey, $key);
141
    }
142
143
    public function setCacheUserData($userId, $key, $data)
144
    {
145
        $cacheKey = $this->getKeyUserId($userId);
146
        return $this->setCache($cacheKey, $key, $data);
147
    }
148
149
    public function deleteAllCacheUserData($userId)
150
    {
151
        $cacheKey = $this->getKeyUserId($userId);
152
        return $this->deleteCache([$cacheKey]);
153
    }
154
155
    public function deleteCacheItemUserData($userId, $key)
156
    {
157
        $cacheKey = $this->getKeyUserId($userId);
158
        return $this->deleteCacheItem($cacheKey, $key);
159
    }
160
161
162
    /**
163
     * Get key of the conversation by chatId
164
     * @param $chatId
165
     * @return string
166
     */
167
    private function getKeyConversation($chatId)
168
    {
169
        return ZanzaraCache::CONVERSATION . strval($chatId);
170
    }
171
172
    public function setConversation($chatId, $data)
173
    {
174
        $key = "state";
175
        $cacheKey = $this->getKeyConversation($chatId);
176
        return $this->setCache($cacheKey, $key, $data);
177
    }
178
179
    /**
180
     * delete a cache iteam and return the promise
181
     * @param $chatId
182
     * @return PromiseInterface
183
     */
184
    public function deleteConversationCache($chatId)
185
    {
186
        return $this->deleteCache([$this->getKeyConversation($chatId)]);
187
    }
188
189
190
    /**
191
     * Use only to call native method of CacheInterface
192
     * @param $name
193
     * @param $arguments
194
     * @return PromiseInterface
195
     */
196
    public function __call($name, $arguments): ?PromiseInterface
197
    {
198
        if ($this->cache) {
199
            return call_user_func_array([$this->cache, $name], $arguments);
200
        }
201
        return null; //should not happen. Don't call cache without instance
202
    }
203
204
205
    /**
206
     * Delete a key inside array stored in cacheKey
207
     * @param $cacheKey
208
     * @param $key
209
     * @return PromiseInterface
210
     */
211
    public function deleteCacheItem($cacheKey, $key)
212
    {
213
        return $this->cache->get($cacheKey)->then(function ($arrayData) use ($cacheKey, $key) {
0 ignored issues
show
Bug introduced by
The method get() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

213
        return $this->cache->/** @scrutinizer ignore-call */ get($cacheKey)->then(function ($arrayData) use ($cacheKey, $key) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
214
            if (!$arrayData) {
215
                return true; //there isn't anything so it's deleted
216
            } else {
217
                unset($arrayData[$key]);
218
            }
219
220
            return $this->cache->set($cacheKey, $arrayData)->then(function ($result) {
221
                if ($result !== true) {
222
                    $this->logger->errorWriteCache($result);
223
                }
224
                return $result;
225
            });
226
        });
227
    }
228
229
230
    /**
231
     * delete a cache iteam and return the promise
232
     * @param array $keys
233
     * @return PromiseInterface
234
     */
235
    public function deleteCache(array $keys)
236
    {
237
        return $this->cache->deleteMultiple($keys)->then(function ($result) {
238
            if ($result !== true) {
239
                $this->logger->errorClearCache($result);
240
            }
241
            return $result;
242
        });
243
    }
244
245
246
    /**
247
     * Get cache item inside array stored in cacheKey
248
     * @param $cacheKey
249
     * @param $key
250
     * @return PromiseInterface
251
     */
252
    public function getCacheItem($cacheKey, $key)
253
    {
254
        return $this->cache->get($cacheKey)->then(function ($arrayData) use ($key) {
255
            if ($arrayData && array_key_exists($key, $arrayData)) {
256
                return $arrayData[$key];
257
            } else {
258
                return null;
259
            }
260
        });
261
    }
262
263
    public function getCache($cacheKey)
264
    {
265
        return $this->cache->get($cacheKey);
266
    }
267
268
    /**
269
     * Wipe entire cache.
270
     * @return PromiseInterface
271
     */
272
    public function wipeCache()
273
    {
274
        return $this->cache->clear();
275
    }
276
277
278
    /**
279
     * set a cache value and return the promise
280
     * @param $cacheKey
281
     * @param $key
282
     * @param $data
283
     * @return PromiseInterface
284
     */
285
    public function setCache($cacheKey, $key, $data)
286
    {
287
        return $this->cache->get($cacheKey)->then(function ($arrayData) use ($key, $data, $cacheKey) {
288
            if (!$arrayData) {
289
                $arrayData = array();
290
                $arrayData[$key] = $data;
291
            } else {
292
                $arrayData[$key] = $data;
293
            }
294
295
            return $this->cache->set($cacheKey, $arrayData)->then(function ($result) {
296
                if ($result !== true) {
297
                    $this->logger->errorWriteCache($result);
298
                }
299
                return $result;
300
            });
301
        });
302
    }
303
304
    /**
305
     * Used by ListenerResolver to call the correct handler stored inside cache
306
     * @param $chatId
307
     * @param $update
308
     * @param $container
309
     * @return PromiseInterface
310
     */
311
    public function callHandlerByChatId($chatId, $update, $container)
312
    {
313
        return $this->cache->get($this->getKeyConversation($chatId))->then(function (array $conversation) use ($update, $chatId, $container) {
0 ignored issues
show
Unused Code introduced by
The import $chatId is not used and could be removed.

This check looks for imports that have been defined, but are not used in the scope.

Loading history...
314
            if ($conversation) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $conversation of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
315
                $handler = $conversation["state"];
316
                $handler(new Context($update, $container));
317
            }
318
        }, function ($err) use ($container, $update) {
0 ignored issues
show
Unused Code introduced by
The import $container is not used and could be removed.

This check looks for imports that have been defined, but are not used in the scope.

Loading history...
319
            $this->logger->errorUpdate($update, $err);
320
        })->otherwise(function ($err, $update, $chatId) {
0 ignored issues
show
Bug introduced by
The method otherwise() does not exist on React\Promise\PromiseInterface. It seems like you code against a sub-type of said class. However, the method does not exist in Zanzara\Test\PromiseWrapper\ZanzaraPromise or React\Promise\CancellablePromiseInterface. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

320
        })->/** @scrutinizer ignore-call */ otherwise(function ($err, $update, $chatId) {
Loading history...
321
            $this->logger->errorUpdate($err, $update);
322
            $this->deleteConversationCache($chatId);
323
        });
324
    }
325
326
}