|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the uSilex framework. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Enrico Fagnoni <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
9
|
|
|
* file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace uSilex\Pimple; |
|
13
|
|
|
|
|
14
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
|
15
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
|
16
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
17
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
18
|
|
|
use OutOfBoundsException; |
|
19
|
|
|
use TypeError; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* Psr15 trait. HTTP Server Request Handlers implementation |
|
23
|
|
|
* |
|
24
|
|
|
* @author Enrico Fagnoni <[email protected]> |
|
25
|
|
|
*/ |
|
26
|
|
|
trait Psr15Trait |
|
27
|
|
|
{ |
|
28
|
|
|
|
|
29
|
|
|
protected $middlewares = []; |
|
30
|
|
|
|
|
31
|
|
|
|
|
32
|
4 |
|
public function registerAsMiddleware(string $servicename) |
|
33
|
|
|
{ |
|
34
|
4 |
|
$this->middlewares[] = $servicename; |
|
35
|
|
|
|
|
36
|
4 |
|
return $this; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
|
|
40
|
5 |
|
protected function handleRunner(ServerRequestInterface $request) : ResponseInterface |
|
41
|
|
|
{ |
|
42
|
5 |
|
$middlewareServiceName = current($this->middlewares); |
|
43
|
5 |
|
if (!$middlewareServiceName) { |
|
44
|
1 |
|
throw new OutOfBoundsException("No middleware to produce an http response"); |
|
45
|
|
|
} |
|
46
|
4 |
|
$middleware = $this[$middlewareServiceName]; |
|
47
|
4 |
|
if( !($middleware instanceof MiddlewareInterface)) { |
|
48
|
1 |
|
throw new TypeError("$middlewareServiceName is not a middleware"); |
|
49
|
|
|
} |
|
50
|
3 |
|
next($this->middlewares); |
|
51
|
|
|
|
|
52
|
|
|
// execute middleware |
|
53
|
3 |
|
$result = $middleware->process($request, $this); |
|
|
|
|
|
|
54
|
|
|
|
|
55
|
3 |
|
return $result; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
|
|
59
|
|
|
/** |
|
60
|
|
|
* Handles a request and produces a response |
|
61
|
|
|
* |
|
62
|
|
|
* May call other collaborating code to generate the response. |
|
63
|
|
|
*/ |
|
64
|
5 |
|
public function handle(ServerRequestInterface $request) : ResponseInterface |
|
65
|
|
|
{ |
|
66
|
5 |
|
reset( $this->middlewares); |
|
67
|
5 |
|
return $this->handleRunner($request); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
} |
|
71
|
|
|
|