Completed
Push — master ( e2a58c...26edc9 )
by Razon
01:19
created

RedisManager::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 1
eloc 4
c 2
b 1
f 0
nc 1
nop 6
dl 0
loc 12
ccs 5
cts 5
cp 1
crap 1
rs 10
1
<?php
2
namespace RazonYang\TokenBucket\Manager;
3
4
use RazonYang\TokenBucket\Manager;
5
use RazonYang\TokenBucket\SerializerInterface;
6
7
class RedisManager extends Manager
8
{
9
    /**
10
     * @var int $ttl time to live.
11
     */
12
    private $ttl = 0;
13
14
    /**
15
     * @var string $prefix key prefix.
16
     */
17
    private $prefix = '';
18
19
    /**
20
     * @var \Redis $redis
21
     */
22
    private $redis;
23
24 2
    public function __construct(
25
        int $capacity,
26
        float $rate,
27
        SerializerInterface $serializer,
28
        \Redis $redis,
29
        int $ttl = 0,
30
        string $prefix = ''
31
    ) {
32 2
        parent::__construct($capacity, $rate, $serializer);
33 2
        $this->redis = $redis;
34 2
        $this->ttl = $ttl;
35 2
        $this->prefix = $prefix;
36 2
    }
37
38 1
    protected function load(string $name)
39
    {
40 1
        return $this->redis->get($this->prefix . $name);
41
    }
42
43 1
    protected function save(string $name, $data)
44
    {
45 1
        if ($this->ttl > 0) {
46 1
            $saved = $this->redis->setEx($this->prefix . $name, $this->ttl, $data);
47
        } else {
48
            $saved = $this->redis->set($this->prefix . $name, $data);
49
        }
50 1
        if (!$saved) {
51
            throw new \RuntimeException('Unable to save allowance: ' . $this->redis->getLastError());
52
        }
53 1
    }
54
}
55