1 | <?php |
||
20 | abstract class AbstractRateLimiter implements RateLimiterInterface |
||
21 | { |
||
22 | /** |
||
23 | * @var int |
||
24 | */ |
||
25 | protected $limit; |
||
26 | |||
27 | /** |
||
28 | * @var int |
||
29 | */ |
||
30 | protected $window; |
||
31 | |||
32 | /** |
||
33 | * @var string |
||
34 | */ |
||
35 | protected $key; |
||
36 | |||
37 | public function __construct(int $limit, int $window) |
||
38 | { |
||
39 | $this->limit = $limit; |
||
40 | $this->window = $window; |
||
41 | } |
||
42 | |||
43 | /** |
||
44 | * {@inheritdoc} |
||
45 | */ |
||
46 | public function getLimit() : int |
||
47 | { |
||
48 | return $this->limit; |
||
49 | } |
||
50 | |||
51 | /** |
||
52 | * {@inheritdoc} |
||
53 | */ |
||
54 | public function getWindow() : int |
||
55 | { |
||
56 | return $this->window; |
||
57 | } |
||
58 | |||
59 | /** |
||
60 | * {@inheritdoc} |
||
61 | */ |
||
62 | public function hit(string $key) |
||
63 | { |
||
64 | $current = $this->getCurrent($key); |
||
65 | |||
66 | if ($current >= $this->limit) { |
||
67 | throw RateLimitExceededException::forKey($key); |
||
68 | } |
||
69 | |||
70 | if (0 === $current) { |
||
71 | $this->init($key); |
||
72 | return; |
||
73 | } |
||
74 | |||
75 | $this->increment($key); |
||
76 | } |
||
77 | |||
78 | /** |
||
79 | * {@inheritdoc} |
||
80 | */ |
||
81 | public function getRemainingAttempts(string $key) : int |
||
82 | { |
||
83 | return max(0, $this->limit - $this->getCurrent($key)); |
||
84 | } |
||
85 | |||
86 | /** |
||
87 | * {@inheritdoc} |
||
88 | */ |
||
89 | public function getResetAt(string $key) : int |
||
90 | { |
||
91 | return (int)ceil(microtime(true) + $this->ttl($key)) |
||
92 | } |
||
|
|||
93 | |||
94 | protected function getCurrent(string $key) : int |
||
95 | { |
||
96 | return $this->get($key, 0); |
||
97 | } |
||
98 | |||
99 | abstract protected function get(string $key, int $default) : int; |
||
100 | |||
101 | abstract protected function init(string $key); |
||
102 | |||
103 | abstract protected function increment(string $key); |
||
104 | |||
105 | abstract protected function ttl(string $key) : float; |
||
106 | } |
||
107 |