Passed
Push — master ( 5a87d9...5af04f )
by Mihail
03:04
created

PredisClient::set()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

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