Completed
Push — master ( 511c4d...dce3f3 )
by Razon
01:21
created

RedisManager::getKey()   A

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 1
dl 0
loc 3
rs 10
ccs 2
cts 2
cp 1
crap 1
1
<?php
2
namespace RazonYang\TokenBucket\Manager;
3
4
use Psr\Log\LoggerInterface;
5
use RazonYang\TokenBucket\Manager;
6
use RazonYang\TokenBucket\SerializerInterface;
7
8
class RedisManager extends Manager
9
{
10
    /**
11
     * @var int $ttl time to live.
12
     */
13
    private $ttl;
14
15
    /**
16
     * @var string $prefix key prefix.
17
     */
18
    private $prefix;
19
20
    /**
21
     * @var \Redis $conn
22
     */
23
    private $conn;
24
25 3
    public function __construct(
26
        int $capacity,
27
        float $rate,
28
        LoggerInterface $logger,
29
        \Redis $conn,
30
        int $ttl = 0,
31
        string $prefix = '',
32
        ?SerializerInterface $serializer = null
33
    ) {
34 3
        parent::__construct($capacity, $rate, $logger, $serializer);
35 3
        $this->conn = $conn;
36 3
        $this->ttl = $ttl;
37 3
        $this->prefix = $prefix;
38 3
    }
39
40 1
    protected function load(string $name)
41
    {
42 1
        return $this->conn->get($this->getKey($name));
43
    }
44
45 2
    protected function save(string $name, $data)
46
    {
47 2
        if ($this->ttl > 0) {
48 1
            $saved = $this->conn->setEx($this->getKey($name), $this->ttl, $data);
49
        } else {
50 1
            $saved = $this->conn->set($this->getKey($name), $data);
51
        }
52 2
        if (!$saved) {
53
            throw new \RuntimeException($this->conn->getLastError());
54
        }
55 2
    }
56
57 2
    protected function getKey(string $name): string
58
    {
59 2
        return $this->prefix . $name;
60
    }
61
}
62