1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is part of the Rate Limit package. |
4
|
|
|
* |
5
|
|
|
* Copyright (c) Nikola Posa |
6
|
|
|
* |
7
|
|
|
* For full copyright and license information, please refer to the LICENSE file, |
8
|
|
|
* located at the package root folder. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace RateLimit; |
12
|
|
|
|
13
|
|
|
use RateLimit\Exception\RateLimitExceededException; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @author Nikola Posa <[email protected]> |
17
|
|
|
*/ |
18
|
|
|
abstract class AbstractRateLimiter implements RateLimiterInterface |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* @var int |
22
|
|
|
*/ |
23
|
|
|
protected $limit; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @var int |
27
|
|
|
*/ |
28
|
|
|
protected $window; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @var string |
32
|
|
|
*/ |
33
|
|
|
protected $key; |
34
|
|
|
|
35
|
24 |
|
public function __construct($limit, $window) |
36
|
|
|
{ |
37
|
24 |
|
$this->limit = (int)$limit; |
38
|
24 |
|
$this->window = (int)$window; |
39
|
24 |
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* {@inheritdoc} |
43
|
|
|
*/ |
44
|
8 |
|
public function getLimit() |
45
|
|
|
{ |
46
|
8 |
|
return $this->limit; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* {@inheritdoc} |
51
|
|
|
*/ |
52
|
2 |
|
public function getWindow() |
53
|
|
|
{ |
54
|
2 |
|
return $this->window; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* {@inheritdoc} |
59
|
|
|
*/ |
60
|
14 |
|
public function hit($key) |
61
|
|
|
{ |
62
|
14 |
|
$key = (string)$key; |
63
|
14 |
|
$current = $this->getCurrent($key); |
64
|
|
|
|
65
|
14 |
|
if ($current >= $this->limit) { |
66
|
7 |
|
throw RateLimitExceededException::forKey($key); |
67
|
|
|
} |
68
|
|
|
|
69
|
14 |
|
if (0 === $current) { |
70
|
14 |
|
$this->init($key); |
71
|
14 |
|
return; |
72
|
|
|
} |
73
|
|
|
|
74
|
1 |
|
$this->increment($key); |
75
|
1 |
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* {@inheritdoc} |
79
|
|
|
*/ |
80
|
10 |
|
public function getRemainingAttempts($key) |
81
|
|
|
{ |
82
|
10 |
|
return max(0, $this->limit - $this->getCurrent((string)$key)); |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
/** |
86
|
|
|
* {@inheritdoc} |
87
|
|
|
*/ |
88
|
10 |
|
public function getResetAt($key) |
89
|
|
|
{ |
90
|
10 |
|
return time() + $this->ttl((string)$key); |
91
|
|
|
} |
92
|
|
|
|
93
|
14 |
|
protected function getCurrent($key) |
94
|
|
|
{ |
95
|
14 |
|
return $this->get((string)$key, 0); |
96
|
|
|
} |
97
|
|
|
|
98
|
|
|
abstract protected function get($key, $default); |
99
|
|
|
|
100
|
|
|
abstract protected function init($key); |
101
|
|
|
|
102
|
|
|
abstract protected function increment($key); |
103
|
|
|
|
104
|
|
|
abstract protected function ttl($key); |
105
|
|
|
} |
106
|
|
|
|