Completed
Push — master ( f8807b...5769db )
by Nikola
06:22
created

RedisRateLimiter   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 81.25%

Importance

Changes 0
Metric Value
dl 0
loc 46
c 0
b 0
f 0
wmc 6
lcom 1
cbo 2
rs 10
ccs 13
cts 16
cp 0.8125

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A handle() 0 21 3
A key() 0 4 1
A ttl() 0 4 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace RateLimit;
6
7
use DateTimeImmutable;
8
use Redis;
9
10
final class RedisRateLimiter implements RateLimiter
11
{
12
    /** @var Redis */
13
    private $redis;
14
15
    /** @var string */
16
    private $keyPrefix;
17
18
    public function __construct(Redis $redis, string $keyPrefix = '')
19
    {
20
        $this->redis = $redis;
21
        $this->keyPrefix = $keyPrefix;
22
    }
23
24
    public function handle(string $identifier, QuotaPolicy $quotaPolicy): Status
25
    {
26
        $key = $this->key($identifier, $quotaPolicy->getInterval());
27 9
28
        $current = (int) $this->redis->get($key);
29 9
30
        if ($current <= $quotaPolicy->getQuota()) {
31 9
            $this->redis->incr($key);
32 9
33
            if ($current === 1) {
34 4
                $this->redis->expire($key, $quotaPolicy->getInterval());
35
            }
36 4
        }
37
38 4
        return Status::from(
39 4
            $identifier,
40
            $current,
41
            $quotaPolicy,
42 3
            (new DateTimeImmutable())->modify('+' . $this->ttl($key) . ' seconds')
43
        );
44
    }
45 4
46
    private function key(string $identifier, int $interval): string
47 4
    {
48 4
        return "{$this->keyPrefix}:{$interval}:$identifier";
49
    }
50
51
    private function ttl(string $key) : int
52
    {
53
        return max((int) ceil($this->redis->pttl($key) / 1000), 0);
54
    }
55
}
56