1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @author PhileCMS |
4
|
|
|
* @link https://philecms.com |
5
|
|
|
* @license http://opensource.org/licenses/MIT |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
namespace Phile\Core; |
9
|
|
|
|
10
|
|
|
use Interop\Http\Server\MiddlewareInterface; |
11
|
|
|
use Interop\Http\Server\RequestHandlerInterface; |
12
|
|
|
use Interop\Http\Factory\ResponseFactoryInterface; |
13
|
|
|
use Psr\Http\Message\ResponseInterface; |
14
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Implements a PSR-15 compatible request handler |
18
|
|
|
*/ |
19
|
|
|
class RequestHandler implements RequestHandlerInterface |
20
|
|
|
{ |
21
|
|
|
/** @var \SplPriorityQueue the middleware to process */ |
22
|
|
|
protected $middleware; |
23
|
|
|
|
24
|
|
|
/** @var ResponseFactoryInterface PSR-17 HTTP response factory */ |
25
|
|
|
protected $responseFactory; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Constructor |
29
|
|
|
* |
30
|
|
|
* @param ResponseFactoryInterface $responseFactory |
31
|
|
|
*/ |
32
|
4 |
|
public function __construct(ResponseFactoryInterface $responseFactory) |
33
|
|
|
{ |
34
|
4 |
|
$this->responseFactory = $responseFactory; |
35
|
4 |
|
$this->middleware = new \SplPriorityQueue(); |
36
|
4 |
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Adds middleware to the the middleware-queue |
40
|
|
|
* |
41
|
|
|
* @param MiddlewareInterface $middleware Middleware to add |
42
|
|
|
* @param int $priority Priority orders middleware in queue |
43
|
|
|
*/ |
44
|
4 |
|
public function add(MiddlewareInterface $middleware, $priority = 10) |
45
|
|
|
{ |
46
|
4 |
|
$this->middleware->insert($middleware, $priority); |
47
|
4 |
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Handle the request and return a response. |
51
|
|
|
* |
52
|
|
|
* @param ServerRequestInterface $request |
53
|
|
|
* @return ResponseInterface |
54
|
|
|
*/ |
55
|
4 |
|
public function handle(ServerRequestInterface $request) |
56
|
|
|
{ |
57
|
4 |
|
if ($this->middleware->key() === 0) { |
58
|
4 |
|
$this->middleware->rewind(); |
59
|
|
|
} |
60
|
4 |
|
if (!$this->middleware->valid()) { |
61
|
|
|
return $this->responseFactory->createResponse(); |
62
|
|
|
} |
63
|
4 |
|
$current = $this->middleware->current(); |
64
|
4 |
|
$this->middleware->next(); |
65
|
4 |
|
return call_user_func_array([$current, 'process'], [$request, $this]); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|