PredisClient::clear()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
/*
3
 * This file is part of the Koded package.
4
 *
5
 * (c) Mihail Binev <[email protected]>
6
 *
7
 * Please view the LICENSE distributed with this source code
8
 * for the full copyright and license information.
9
 */
10
11
namespace Koded\Caching\Client;
12
13
use Koded\Caching\Cache;
14
use Koded\Stdlib\Serializer;
15
use function Koded\Caching\verify_key;
16
17
/**
18
 * Class PredisClient uses the Predis library.
19
 *
20
 * @property \Predis\Client client
21
 */
22
final class PredisClient implements Cache
23
{
24
    use ClientTrait, MultiplesTrait;
25
26
    private Serializer $serializer;
27
28 62
    public function __construct(\Predis\Client $client, Serializer $serializer, int $ttl = null)
29
    {
30 62
        $this->client = $client;
31 62
        $this->serializer = $serializer;
32 62
        $this->ttl = $ttl;
33
    }
34
35 43
    public function get(string $key, mixed $default = null): mixed
36
    {
37 43
        return $this->has($key)
38 36
            ? $this->serializer->unserialize($this->client->get($key))
39 43
            : $default;
40
    }
41
42 42
    public function set(string $key, mixed $value, null|int|\DateInterval $ttl = null): bool
43
    {
44 42
        verify_key($key);
45 42
        $expiration = $this->secondsWithGlobalTtl($ttl);
46 42
        if (null === $ttl && 0 === $expiration) {
47 40
            return 'OK' === $this->client->set($key, $this->serializer->serialize($value))->getPayload();
48
        }
49 3
        if ($expiration > 0) {
50 2
            return 'OK' === $this->client->setex($key, $expiration, $this->serializer->serialize($value))->getPayload();
51
        }
52 1
        $this->client->del($key);
53 1
        return true;
54
    }
55
56
57 5
    public function delete(string $key): bool
58
    {
59 5
        if (false === $this->has($key)) {
60 4
            return true;
61
        }
62 4
        return 1 === $this->client->del($key);
63
    }
64
65 61
    public function clear(): bool
66
    {
67 61
        return 'OK' === $this->client->flushdb()->getPayload();
68
    }
69
70 44
    public function has(string $key): bool
71
    {
72 44
        verify_key($key);
73 44
        return 1 === $this->client->exists($key);
74
    }
75
}
76