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

RedisManager   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Test Coverage

Coverage 85.71%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 15
c 2
b 1
f 0
dl 0
loc 45
ccs 12
cts 14
cp 0.8571
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A load() 0 3 1
A save() 0 9 3
A __construct() 0 12 1
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