|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Yii\Web\RateLimiter; |
|
6
|
|
|
|
|
7
|
|
|
use Psr\Http\Message\ResponseFactoryInterface; |
|
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
9
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
10
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
|
11
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
|
12
|
|
|
|
|
13
|
|
|
final class RateLimiter implements MiddlewareInterface |
|
14
|
|
|
{ |
|
15
|
|
|
private int $limit = 1000; |
|
16
|
|
|
|
|
17
|
|
|
private CounterInterface $counter; |
|
18
|
|
|
|
|
19
|
|
|
private ResponseFactoryInterface $responseFactory; |
|
20
|
|
|
|
|
21
|
|
|
private bool $autoincrement = true; |
|
22
|
|
|
|
|
23
|
|
|
public function __construct(CounterInterface $counter, ResponseFactoryInterface $responseFactory) |
|
24
|
|
|
{ |
|
25
|
|
|
$this->counter = $counter; |
|
26
|
|
|
$this->responseFactory = $responseFactory; |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
|
30
|
|
|
{ |
|
31
|
|
|
$this->counter->init($request); |
|
32
|
|
|
|
|
33
|
|
|
if (!$this->isAllowed()) { |
|
34
|
|
|
return $this->createErrorResponse(); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
if ($this->autoincrement) { |
|
38
|
|
|
$this->counter->increment(); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
return $handler->handle($request); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
public function withLimit(int $limit): self |
|
45
|
|
|
{ |
|
46
|
|
|
$this->limit = $limit; |
|
47
|
|
|
|
|
48
|
|
|
return $this; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
public function setAutoIncrement(bool $increment): self |
|
52
|
|
|
{ |
|
53
|
|
|
$this->autoincrement = $increment; |
|
54
|
|
|
|
|
55
|
|
|
return $this; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
private function createErrorResponse(): ResponseInterface |
|
59
|
|
|
{ |
|
60
|
|
|
$response = $this->responseFactory->createResponse(429); |
|
61
|
|
|
$response->getBody()->write('Too Many Requests'); |
|
62
|
|
|
|
|
63
|
|
|
return $response; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
private function isAllowed(): bool |
|
67
|
|
|
{ |
|
68
|
|
|
return $this->counter->getCounterValue() < $this->limit; |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|