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

PredisClient   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 22
c 2
b 0
f 0
dl 0
loc 62
ccs 27
cts 27
cp 1
rs 10
wmc 11

6 Methods

Rating   Name   Duplication   Size   Complexity  
A delete() 0 7 2
A clear() 0 3 1
A set() 0 16 4
A get() 0 5 2
A __construct() 0 5 1
A has() 0 5 1
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