|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* It's free open-source software released under the MIT License. |
|
5
|
|
|
* |
|
6
|
|
|
* @author Anatoly Fenric <[email protected]> |
|
7
|
|
|
* @copyright Copyright (c) 2018, Anatoly Fenric |
|
8
|
|
|
* @license https://github.com/sunrise-php/http-router/blob/master/LICENSE |
|
9
|
|
|
* @link https://github.com/sunrise-php/http-router |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace Sunrise\Http\Router\RequestHandler; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* Import classes |
|
16
|
|
|
*/ |
|
17
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
18
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
19
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
|
20
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
|
21
|
|
|
use SplQueue; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* QueueableRequestHandler |
|
25
|
|
|
*/ |
|
26
|
|
|
class QueueableRequestHandler implements RequestHandlerInterface |
|
27
|
|
|
{ |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* The request handler queue |
|
31
|
|
|
* |
|
32
|
|
|
* @var SplQueue |
|
33
|
|
|
*/ |
|
34
|
|
|
private $queue; |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* The request handler endpoint |
|
38
|
|
|
* |
|
39
|
|
|
* @var RequestHandlerInterface |
|
40
|
|
|
*/ |
|
41
|
|
|
private $endpoint; |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* Constructor of the class |
|
45
|
|
|
* |
|
46
|
|
|
* @param RequestHandlerInterface $endpoint |
|
47
|
|
|
*/ |
|
48
|
|
|
public function __construct(RequestHandlerInterface $endpoint) |
|
49
|
|
|
{ |
|
50
|
|
|
$this->queue = new SplQueue(); |
|
51
|
|
|
$this->endpoint = $endpoint; |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
/** |
|
55
|
|
|
* Adds the given middleware(s) to the request handler queue |
|
56
|
|
|
* |
|
57
|
|
|
* @param MiddlewareInterface ...$middlewares |
|
58
|
|
|
* |
|
59
|
|
|
* @return void |
|
60
|
|
|
*/ |
|
61
|
|
|
public function add(MiddlewareInterface ...$middlewares) : void |
|
62
|
|
|
{ |
|
63
|
|
|
foreach ($middlewares as $middleware) { |
|
64
|
|
|
$this->queue->enqueue($middleware); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
/** |
|
69
|
|
|
* {@inheritDoc} |
|
70
|
|
|
*/ |
|
71
|
|
|
public function handle(ServerRequestInterface $request) : ResponseInterface |
|
72
|
|
|
{ |
|
73
|
|
|
if (!$this->queue->isEmpty()) { |
|
74
|
|
|
return $this->queue->dequeue()->process($request, $this); |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
|
|
return $this->endpoint->handle($request); |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
|