RateLimitMiddleware   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 0
Metric Value
dl 0
loc 45
c 0
b 0
f 0
wmc 3
lcom 0
cbo 3
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A __invoke() 0 9 2
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