Passed
Pull Request — master (#8)
by Moiseenko
05:34
created

RedisCache::isExpiredTtl()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 1
c 2
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Cache\Redis;
6
7
use DateInterval;
8
use DateTime;
9
use Predis\Client;
10
use Predis\ClientInterface;
11
use Predis\Connection\ConnectionInterface;
12
use Predis\Connection\StreamConnection;
13
use Predis\Response\Status;
14
use Psr\SimpleCache\CacheInterface;
15
use Traversable;
16
17
use function array_fill_keys;
18
use function array_keys;
19
use function array_map;
20
use function count;
21
use function iterator_to_array;
22
use function serialize;
23
use function strpbrk;
24
use function unserialize;
25
26
/**
27
 * RedisCache stores cache data in a Redis.
28
 *
29
 * Please refer to {@see CacheInterface} for common cache operations that are supported by RedisCache.
30
 */
31
final class RedisCache implements CacheInterface
32
{
33
    /**
34
     * @var array<ConnectionInterface>|ConnectionInterface $connections Predis connections instance to use
35
     */
36
    private ConnectionInterface|array $connections;
37
38
    /**
39
     * @param ClientInterface $client Predis client instance to use.
40
     */
41 227
    public function __construct(private ClientInterface $client)
42
    {
43 227
        $this->connections = $this->client->getConnection();
44
    }
45
46
    /**
47
     * Checking Predis cluster usage
48
     *
49
     * @return bool
50
     */
51 227
    public function isCluster(): bool
52
    {
53
        /** @psalm-suppress MixedAssignment, PossibleRawObjectIteration */
54 227
        foreach ($this->connections as $connection) {
55
            /** @var StreamConnection $connection */
56 109
            $cluster = (new Client($connection->getParameters()))->info('Cluster');
57
            /** @psalm-suppress MixedArrayAccess */
58 109
            if (isset($cluster['Cluster']['cluster_enabled']) && 1 === (int)$cluster['Cluster']['cluster_enabled']) {
59 109
                return true;
60
            }
61
        }
62
63 118
        return false;
64
    }
65
66
    /**
67
     * @param string $key
68
     * @param mixed|null $default
69
     *
70
     * @throws InvalidArgumentException
71
     *
72
     * @return mixed
73
     */
74 134
    public function get(string $key, mixed $default = null): mixed
75
    {
76 134
        $this->validateKey($key);
77
        /** @var string|null $value */
78 130
        $value = $this->client->get($key);
79 130
        return $value === null ? $default : unserialize($value);
80
    }
81
82
    /**
83
     * @param string $key
84
     * @param mixed $value
85
     * @param DateInterval|int|null $ttl
86
     *
87
     * @throws InvalidArgumentException
88
     *
89
     * @return bool
90
     */
91 175
    public function set(string $key, mixed $value, null|int|DateInterval $ttl = null): bool
92
    {
93 175
        $ttl = $this->normalizeTtl($ttl);
94
95 175
        if ($this->isExpiredTtl($ttl)) {
96 1
            return $this->delete($key);
97
        }
98
99 174
        $this->validateKey($key);
100
101
        /** @var Status|null $result */
102 172
        $result = $this->isInfinityTtl($ttl)
103 148
            ? $this->client->set($key, serialize($value))
104 24
            : $this->client->set($key, serialize($value), 'EX', $ttl);
105
106 172
        return $result !== null;
107
    }
108
109
    /**
110
     * @param string $key
111
     *
112
     * @throws InvalidArgumentException
113
     *
114
     * @return bool
115
     */
116 31
    public function delete(string $key): bool
117
    {
118 31
        return !$this->has($key) || $this->client->del($key) === 1;
119
    }
120
121
    /**
122
     * If a cluster is used, all nodes will be cleared
123
     *
124
     * @return bool
125
     */
126 227
    public function clear(): bool
127
    {
128 227
        if ($this->isCluster()) {
129
            /** @psalm-suppress MixedAssignment, PossibleRawObjectIteration */
130 109
            foreach ($this->connections as $connection) {
131
                /** @var StreamConnection $connection */
132 109
                $client = new Client($connection->getParameters());
133 109
                $client->flushdb();
134
            }
135 109
            return true;
136
        }
137
138 118
        return $this->client->flushdb() !== null;
139
    }
140
141
    /**
142
     * @param iterable<string> $keys
143
     * @param mixed $default
144
     *
145
     * @throws InvalidArgumentException
146
     *
147
     * @return iterable<string, mixed>
148
     */
149 18
    public function getMultiple(iterable $keys, mixed $default = null): iterable
150
    {
151
        /** @var string[] $keys */
152 18
        $keys = $this->iterableToArray($keys);
153 18
        $this->validateKeys($keys);
154 12
        $values = array_fill_keys($keys, $default);
155
156 12
        if ($this->isCluster()) {
157 5
            foreach ($keys as $key) {
158
                /** @var string|null $value */
159 5
                $value = $this->get($key);
160 5
                if (null !== $value) {
161
                    /** @psalm-suppress MixedAssignment */
162 4
                    $values[$key] = unserialize($value);
163
                }
164
            }
165
        } else {
166
            /** @var null[]|string[] $valuesFromCache */
167 7
            $valuesFromCache = $this->client->mget($keys);
168
169 7
            $i = 0;
170
            /** @psalm-suppress MixedAssignment */
171 7
            foreach ($values as $key => $value) {
172 7
                $values[$key] = isset($valuesFromCache[$i]) ? unserialize($valuesFromCache[$i]) : $value;
173 7
                $i++;
174
            }
175
        }
176
177 12
        return $values;
178
    }
179
180
    /**
181
     * @param iterable $values
182
     * @param DateInterval|int|null $ttl
183
     *
184
     * @throws InvalidArgumentException
185
     *
186
     * @return bool
187
     */
188 18
    public function setMultiple(iterable $values, null|int|DateInterval $ttl = null): bool
189
    {
190 18
        $values = $this->iterableToArray($values);
191 18
        $keys = array_map('\strval', array_keys($values));
192 18
        $this->validateKeys($keys);
193 16
        $ttl = $this->normalizeTtl($ttl);
194 16
        $serializeValues = [];
195
196 16
        if ($this->isExpiredTtl($ttl)) {
197 1
            return $this->deleteMultiple($keys);
198
        }
199
200
        /** @var mixed $value */
201 15
        foreach ($values as $key => $value) {
202 15
            $serializeValues[$key] = serialize($value);
203
        }
204
205 15
        $results = [];
206 15
        if ($this->isCluster()) {
207 4
            foreach ($serializeValues as $key => $value) {
208 4
                $this->set((string)$key, $value, $this->isInfinityTtl($ttl) ? null : $ttl);
209
            }
210
        } else {
211 11
            if ($this->isInfinityTtl($ttl)) {
212 8
                $this->client->mset($serializeValues);
213 8
                return true;
214
            }
215
216 3
            $this->client->multi();
217 3
            $this->client->mset($serializeValues);
218
219 3
            foreach ($keys as $key) {
220 3
                $this->client->expire($key, (int)$ttl);
221
            }
222
223
            /** @var array|null $results */
224 3
            $results = $this->client->exec();
225
        }
226
227 7
        return !in_array(null, (array)$results, true);
228
    }
229
230
    /**
231
     * @param iterable $keys
232
     *
233
     * @throws InvalidArgumentException
234
     *
235
     * @return bool
236
     */
237 8
    public function deleteMultiple(iterable $keys): bool
238
    {
239 8
        $keys = $this->iterableToArray($keys);
240
241
        /** @psalm-suppress MixedAssignment, MixedArgument */
242 8
        foreach ($keys as $index => $key) {
243 8
            if (!$this->has($key)) {
244 3
                unset($keys[$index]);
245
            }
246
        }
247
248
        /** @psalm-suppress MixedArgumentTypeCoercion */
249 4
        return empty($keys) || $this->client->del($keys) === count($keys);
250
    }
251
252
    /**
253
     * @param string $key
254
     *
255
     * @throws InvalidArgumentException
256
     *
257
     * @return bool
258
     */
259 64
    public function has(string $key): bool
260
    {
261 64
        $this->validateKey($key);
262
        /** @var int $ttl */
263 52
        $ttl = $this->client->ttl($key);
264
        /** "-1" - if the key exists but has no associated expire {@see https://redis.io/commands/ttl}. */
265 52
        return $ttl > 0 || $ttl === -1;
266
    }
267
268
    /**
269
     * Normalizes cache TTL handling `null` value, strings and {@see DateInterval} objects.
270
     *
271
     * @param DateInterval|int|string|null $ttl The raw TTL.
272
     *
273
     * @return int|null TTL value as UNIX timestamp.
274
     */
275 200
    private function normalizeTtl(null|int|string|DateInterval $ttl): ?int
276
    {
277 200
        if ($ttl === null) {
278 160
            return null;
279
        }
280
281 40
        if ($ttl instanceof DateInterval) {
282 4
            return (new DateTime('@0'))
283 4
                ->add($ttl)
284 4
                ->getTimestamp();
285
        }
286
287 36
        return (int) $ttl;
288
    }
289
290
    /**
291
     * Converts iterable to array.
292
     *
293
     * @return array
294
     */
295 30
    private function iterableToArray(iterable $iterable): array
296
    {
297
        /** @psalm-suppress RedundantCast */
298 30
        return $iterable instanceof Traversable ? iterator_to_array($iterable) : (array) $iterable;
299
    }
300
301
    /**
302
     * @param string $key
303
     *
304
     * @throws InvalidArgumentException
305
     */
306 208
    private function validateKey(string $key): void
307
    {
308 208
        if ($key === '' || strpbrk($key, '{}()/\@:')) {
309 22
            throw new InvalidArgumentException('Invalid key value.');
310
        }
311
    }
312
313
    /**
314
     * @param string[] $keys
315
     *
316
     * @throws InvalidArgumentException
317
     */
318 26
    private function validateKeys(array $keys): void
319
    {
320 26
        if ([] === $keys) {
321 4
            throw new InvalidArgumentException('Invalid key values.');
322
        }
323
324 22
        foreach ($keys as $key) {
325 22
            $this->validateKey($key);
326
        }
327
    }
328
329
    /**
330
     * @param int|null $ttl
331
     *
332
     * @return bool
333
     */
334 186
    private function isExpiredTtl(?int $ttl): bool
335
    {
336 186
        return $ttl !== null && $ttl <= 0;
337
    }
338
339
    /**
340
     * @param int|null $ttl
341
     *
342
     * @return bool
343
     */
344 183
    private function isInfinityTtl(?int $ttl): bool
345
    {
346 183
        return $ttl === null;
347
    }
348
}
349