1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Chadicus\Psr\Http\ServerMiddleware; |
4
|
|
|
|
5
|
|
|
use Chadicus\Psr\Middleware\MiddlewareInterface; |
6
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
7
|
|
|
use Psr\Http\Message\ResponseInterface; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Middleware for limiting client requests. |
11
|
|
|
*/ |
12
|
|
|
final class RateLimitMiddleware implements MiddlewareInterface |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var ClientExtractorInterface |
16
|
|
|
*/ |
17
|
|
|
private $clientExtractor; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var LimitedResponseFactoryInterface |
21
|
|
|
*/ |
22
|
|
|
private $responseFactory; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Create a new instance of the middleware. |
26
|
|
|
* |
27
|
|
|
* @param ClientExtractorInterface $clientExtractor Obtains the client from the HTTP request. |
28
|
|
|
* @param LimitedResponseFactoryInterface $responseFactory Factory object for creating 429 responses. |
29
|
|
|
*/ |
30
|
|
|
public function __construct( |
31
|
|
|
ClientExtractorInterface $clientExtractor, |
32
|
|
|
LimitedResponseFactoryInterface $responseFactory |
33
|
|
|
) { |
34
|
|
|
$this->clientExtractor = $clientExtractor; |
35
|
|
|
$this->responseFactory = $responseFactory; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Execute this middleware. |
40
|
|
|
* |
41
|
|
|
* @param ServerRequestInterface $request The PSR7 request. |
42
|
|
|
* @param ResponseInterface $response The PSR7 response. |
43
|
|
|
* @param callable $next The Next middleware. |
44
|
|
|
* |
45
|
|
|
* @return ResponseInterface |
46
|
|
|
*/ |
47
|
|
|
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) |
48
|
|
|
{ |
49
|
|
|
$client = $this->clientExtractor->extract($request); |
50
|
|
|
if (!$client->canMakeRequest($request)) { |
51
|
|
|
return $this->responseFactory->createResponse($client); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
return $next($request, $response); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|