RedisRateLimiter::getRedis()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.0261

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 11
rs 10
ccs 6
cts 7
cp 0.8571
cc 3
nc 3
nop 0
crap 3.0261
1
<?php
2
namespace RazonYang\Yii2\RateLimiter;
3
4
use RazonYang\TokenBucket\ManagerInterface;
5
use RazonYang\TokenBucket\Manager\RedisManager;
6
use RazonYang\Yii2\RateLimiter\BaseRateLimiter;
7
8
class RedisRateLimiter extends BaseRateLimiter
9
{
10
    /**
11
     * @var string $hostname
12
     */
13
    public $hostname = 'localhost';
14
15
    /**
16
     * @var int $port
17
     */
18
    public $port = 6379;
19
20
    /**
21
     * @var string $password
22
     */
23
    public $password = '';
24
25
    public $ttl = 3600;
26
27
    public $prefix = 'rate_limiter:';
28
29 2
    protected function initManager(): ManagerInterface
30
    {
31 2
        return new RedisManager($this->capacity, $this->rate, $this->getLogger(), $this->getRedis(), $this->ttl, $this->prefix);
32
    }
33
34
    private $redis;
35
36 2
    protected function getRedis(): \Redis
37
    {
38 2
        if ($this->redis === null) {
39 2
            $this->redis = new \Redis();
40 2
            $this->redis->connect($this->hostname, $this->port);
41 2
            if ($this->password !== '') {
42
                $this->redis->auth($this->password);
43
            }
44
        }
45
46 2
        return $this->redis;
47
    }
48
}
49