Completed
Pull Request — master (#24)
by Julián
06:48
created

PredisRateLimiter   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 1
dl 0
loc 33
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A getCurrent() 0 4 1
A updateCounter() 0 10 2
A ttl() 0 4 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace RateLimit;
6
7
use Predis\ClientInterface;
8
9
final class PredisRateLimiter extends AbstractTTLRateLimiter
10
{
11
    /** @var ClientInterface */
12
    private $predis;
13
14
    public function __construct(ClientInterface $predis, string $keyPrefix = '')
15
    {
16
        parent::__construct($keyPrefix);
17
18
        $this->predis = $predis;
19
    }
20
21
    protected function getCurrent(string $key): int
22
    {
23
        return (int) $this->predis->get($key);
24
    }
25
26
    protected function updateCounter(string $key, int $interval): int
27
    {
28
        $current = $this->predis->incr($key);
29
30
        if ($current === 1) {
31
            $this->predis->expire($key, $interval);
32
        }
33
34
        return $current;
35
    }
36
37
    protected function ttl(string $key): int
38
    {
39
        return max((int) ceil($this->predis->pttl($key) / 1000), 0);
40
    }
41
}
42