1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Simply\Application\Handler; |
4
|
|
|
|
5
|
|
|
use Psr\Http\Message\ResponseInterface as Response; |
6
|
|
|
use Psr\Http\Message\ServerRequestInterface as Request; |
7
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
8
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* A middleware stack that acts like a request handler. |
12
|
|
|
* @author Riikka Kalliomäki <[email protected]> |
13
|
|
|
* @copyright Copyright (c) 2018 Riikka Kalliomäki |
14
|
|
|
* @license http://opensource.org/licenses/mit-license.php MIT License |
15
|
|
|
*/ |
16
|
|
|
class MiddlewareHandler implements RequestHandlerInterface |
17
|
|
|
{ |
18
|
|
|
/** @var MiddlewareInterface[] List of middleware instances to call */ |
19
|
|
|
private $stack; |
20
|
|
|
|
21
|
|
|
/** @var RequestHandlerInterface The fallback request handler */ |
22
|
|
|
private $fallback; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* MiddlewareHandler constructor. |
26
|
|
|
* @param RequestHandlerInterface $fallback The fallback request handler to call |
27
|
|
|
*/ |
28
|
12 |
|
public function __construct(RequestHandlerInterface $fallback) |
29
|
|
|
{ |
30
|
12 |
|
$this->stack = []; |
31
|
12 |
|
$this->fallback = $fallback; |
32
|
12 |
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Adds a new middleware to the stack. |
36
|
|
|
* @param MiddlewareInterface $middleware Additional middleware to add to the stack |
37
|
|
|
*/ |
38
|
12 |
|
public function push(MiddlewareInterface $middleware): void |
39
|
|
|
{ |
40
|
12 |
|
$this->stack[] = $middleware; |
41
|
12 |
|
} |
42
|
|
|
|
43
|
|
|
/** {@inheritdoc} */ |
44
|
12 |
|
public function handle(Request $request): Response |
45
|
|
|
{ |
46
|
12 |
|
$stack = $this->stack; |
47
|
|
|
|
48
|
|
|
$handler = new CallbackHandler(function (Request $request) use (& $stack, & $handler): Response { |
49
|
12 |
|
$middleware = array_shift($stack); |
50
|
|
|
|
51
|
12 |
|
if ($middleware instanceof MiddlewareInterface) { |
52
|
12 |
|
return $middleware->process($request, $handler); |
53
|
|
|
} |
54
|
|
|
|
55
|
2 |
|
return $this->fallback->handle($request); |
56
|
12 |
|
}); |
57
|
|
|
|
58
|
12 |
|
return $handler->handle($request); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|