1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is part of the Shieldon package. |
4
|
|
|
* |
5
|
|
|
* (c) Terry L. <[email protected]> |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
declare(strict_types=1); |
12
|
|
|
|
13
|
|
|
namespace Shieldon\Psr15; |
14
|
|
|
|
15
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
16
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
17
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
18
|
|
|
use Psr\Http\Message\ResponseInterface; |
19
|
|
|
use Shieldon\Psr7\Response; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* PSR-15 Middleware |
23
|
|
|
*/ |
24
|
|
|
class RequestHandler implements RequestHandlerInterface |
25
|
|
|
{ |
26
|
|
|
/** |
27
|
|
|
* Middlewares in the queue are ready to run. |
28
|
|
|
* |
29
|
|
|
* @var array |
30
|
|
|
*/ |
31
|
|
|
protected $queue = []; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* After the last middleware has been called, a fallback handler should |
35
|
|
|
* parse the request and give an appropriate response. |
36
|
|
|
* |
37
|
|
|
* @var RequestHandlerInterface|null |
38
|
|
|
*/ |
39
|
|
|
protected $fallbackHandler = null; |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* RequestHandler constructor. |
43
|
|
|
* |
44
|
|
|
* @param RequestHandler|null $finalRequestHandler A valid resource. |
45
|
|
|
*/ |
46
|
3 |
|
public function __construct(?RequestHandlerInterface $fallbackHandler = null) |
47
|
|
|
{ |
48
|
3 |
|
if ($fallbackHandler instanceof RequestHandlerInterface) { |
49
|
1 |
|
$this->fallbackHandler = $fallbackHandler; |
50
|
|
|
} |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* {@inheritdoc} |
55
|
|
|
*/ |
56
|
3 |
|
public function add(MiddlewareInterface $middleware) |
57
|
|
|
{ |
58
|
3 |
|
$this->queue[] = $middleware; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* {@inheritdoc} |
63
|
|
|
*/ |
64
|
3 |
|
public function handle(ServerRequestInterface $request): ResponseInterface |
65
|
|
|
{ |
66
|
3 |
|
if (0 === count($this->queue)) { |
67
|
2 |
|
return $this->final($request); |
68
|
|
|
} |
69
|
|
|
|
70
|
3 |
|
$middleware = array_shift($this->queue); |
71
|
|
|
|
72
|
3 |
|
return $middleware->process($request, $this); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* This is the final, there is no middleware needed to execute, pasre the |
77
|
|
|
* layered request and give a parsed response. |
78
|
|
|
* |
79
|
|
|
* @param ServerRequestInterface $request |
80
|
|
|
* |
81
|
|
|
* @return ResponseInterface |
82
|
|
|
*/ |
83
|
2 |
|
protected function final(ServerRequestInterface $request): ResponseInterface |
84
|
|
|
{ |
85
|
2 |
|
if (!$this->fallbackHandler) { |
86
|
1 |
|
return new Response(); |
87
|
|
|
} |
88
|
|
|
|
89
|
1 |
|
return $this->fallbackHandler->handle($request); |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|