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

AbstractElapsedTimeRateLimiter   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 2
dl 0
loc 59
ccs 28
cts 28
cp 1
rs 10
c 0
b 0
f 0

8 Methods

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