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

AbstractTTLRateLimiter::ttl()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1
c 0
b 0
f 0
nc 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
    /**
12
     * @var string
13
     */
14
    private $keyPrefix;
15
16
    public function __construct(string $keyPrefix = '')
17
    {
18
        $this->keyPrefix = $keyPrefix;
19
    }
20
21
    final public function limit(string $identifier, Rate $rate): void
22
    {
23
        $key = $this->key($identifier, $rate->getInterval());
24
25
        $current = $this->getCurrent($key);
26
        if ($current >= $rate->getOperations()) {
27
            throw LimitExceeded::for($identifier, $rate);
28
        }
29
30
        $this->updateCounter($key, $rate->getInterval());
31
    }
32
33
    final public function limitSilently(string $identifier, Rate $rate): Status
34
    {
35
        $key = $this->key($identifier, $rate->getInterval());
36
37
        $current = $this->getCurrent($key);
38
        if ($current <= $rate->getOperations()) {
39
            $current = $this->updateCounter($key, $rate->getInterval());
40
        }
41
42
        return Status::from(
43
            $identifier,
44
            $current,
45
            $rate->getOperations(),
46
            time() + $this->ttl($key)
47
        );
48
    }
49
50
    private function key(string $identifier, int $interval): string
51
    {
52
        return \sprintf('%s%s:%d', $this->keyPrefix, $identifier, $interval);
53
    }
54
55
    abstract protected function getCurrent(string $key): int;
56
57
    abstract protected function updateCounter(string $key, int $interval): int;
58
59
    abstract protected function ttl(string $key): int;
60
}
61