Completed
Pull Request — master (#24)
by Julián
04:37
created

AbstractTTLRateLimiter   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 2
dl 0
loc 50
ccs 22
cts 22
cp 1
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 10
    public function __construct(string $keyPrefix = '')
15
    {
16 10
        $this->keyPrefix = $keyPrefix;
17 10
    }
18
19 4
    final public function limit(string $identifier, Rate $rate): void
20
    {
21 4
        $key = $this->key($identifier, $rate->getInterval());
22
23 4
        $current = $this->getCurrent($key);
24 4
        if ($current >= $rate->getOperations()) {
25 4
            throw LimitExceeded::for($identifier, $rate);
26
        }
27
28 4
        $this->updateCounter($key, $rate->getInterval());
29 4
    }
30
31 6
    final public function limitSilently(string $identifier, Rate $rate): Status
32
    {
33 6
        $key = $this->key($identifier, $rate->getInterval());
34
35 6
        $current = $this->getCurrent($key);
36 6
        if ($current <= $rate->getOperations()) {
37 6
            $current = $this->updateCounter($key, $rate->getInterval());
38
        }
39
40 6
        return Status::from(
41 6
            $identifier,
42 6
            $current,
43 6
            $rate->getOperations(),
44 6
            time() + $this->ttl($key)
45
        );
46
    }
47
48 10
    private function key(string $identifier, int $interval): string
49
    {
50 10
        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