Completed
Pull Request — master (#24)
by Julián
07:27
created

AbstractTTLRateLimiter   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 2
dl 0
loc 50
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A limit() 0 11 2
A limitSilently() 0 16 2
A key() 0 4 1
getCurrent() 0 1 ?
updateCounter() 0 1 ?
ttl() 0 1 ?
1
<?php
2
3
declare(strict_types=1);
4
5
namespace RateLimit;
6
7
use RateLimit\Exception\LimitExceeded;
8
9
abstract class AbstractTTLRateLimiter implements RateLimiter, SilentRateLimiter
10
{
11
    /** @var string */
12
    private $keyPrefix;
13
14
    public function __construct(string $keyPrefix = '')
15
    {
16
        $this->keyPrefix = $keyPrefix;
17
    }
18
19
    final public function limit(string $identifier, Rate $rate): void
20
    {
21
        $key = $this->key($identifier, $rate->getInterval());
22
23
        $current = $this->getCurrent($key);
24
        if ($current >= $rate->getOperations()) {
25
            throw LimitExceeded::for($identifier, $rate);
26
        }
27
28
        $this->updateCounter($key, $rate->getInterval());
29
    }
30
31
    final public function limitSilently(string $identifier, Rate $rate): Status
32
    {
33
        $key = $this->key($identifier, $rate->getInterval());
34
35
        $current = $this->getCurrent($key);
36
        if ($current <= $rate->getOperations()) {
37
            $current = $this->updateCounter($key, $rate->getInterval());
38
        }
39
40
        return Status::from(
41
            $identifier,
42
            $current,
43
            $rate->getOperations(),
44
            time() + $this->ttl($key)
45
        );
46
    }
47
48
    private function key(string $identifier, int $interval): string
49
    {
50
        return \sprintf('%s%s:%d', $this->keyPrefix, $identifier, $interval);
51
    }
52
53
    abstract protected function getCurrent(string $key): int;
54
55
    abstract protected function updateCounter(string $key, int $interval): int;
56
57
    abstract protected function ttl(string $key): int;
58
}
59