1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
/* |
3
|
|
|
* This file is part of coisa/http. |
4
|
|
|
* |
5
|
|
|
* (c) Felipe Sayão Lobato Abreu <[email protected]> |
6
|
|
|
* |
7
|
|
|
* This source file is subject to the license that is bundled |
8
|
|
|
* with this source code in the file LICENSE. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace CoiSA\Http\Handler; |
12
|
|
|
|
13
|
|
|
use CoiSA\Http\Middleware\PregMatchRequestTargetMiddleware; |
14
|
|
|
use CoiSA\Http\Middleware\RequestMethodMiddleware; |
15
|
|
|
use Psr\Http\Message\ResponseInterface; |
16
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
17
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
18
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Class RouterHandler |
22
|
|
|
* |
23
|
|
|
* @package CoiSA\Http\Handler |
24
|
|
|
*/ |
25
|
|
|
final class RouterHandler implements RequestHandlerInterface |
26
|
|
|
{ |
27
|
|
|
/** |
28
|
|
|
* @var RequestHandlerInterface |
29
|
|
|
*/ |
30
|
|
|
private $notFoundHandler; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @var MiddlewareInterface[] |
34
|
|
|
*/ |
35
|
|
|
private $routes; |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* RouterHandler constructor. |
39
|
|
|
* |
40
|
|
|
* @param RequestHandlerInterface $notFoundHandler |
41
|
|
|
*/ |
42
|
|
|
public function __construct(RequestHandlerInterface $notFoundHandler) |
43
|
|
|
{ |
44
|
|
|
$this->notFoundHandler = $notFoundHandler; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @param string $method |
49
|
|
|
* @param string $regex |
50
|
|
|
* @param RequestHandlerInterface $requestHandler |
51
|
|
|
*/ |
52
|
|
|
public function addRoute(string $method, string $regex, RequestHandlerInterface $requestHandler): void |
53
|
|
|
{ |
54
|
|
|
$middleware = new RequestMethodMiddleware($method, $requestHandler); |
55
|
|
|
$this->routes[] = new PregMatchRequestTargetMiddleware( |
56
|
|
|
$regex, |
57
|
|
|
new MiddlewareHandler($middleware, $this) |
58
|
|
|
); |
59
|
|
|
\reset($this->routes); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @param ServerRequestInterface $request |
64
|
|
|
* |
65
|
|
|
* @return ResponseInterface |
66
|
|
|
*/ |
67
|
|
|
public function handle(ServerRequestInterface $request): ResponseInterface |
68
|
|
|
{ |
69
|
|
|
$middleware = \current($this->routes); |
70
|
|
|
|
71
|
|
|
if (!$middleware) { |
72
|
|
|
\reset($this->routes); |
73
|
|
|
|
74
|
|
|
return $this->notFoundHandler->handle($request); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
\next($this->routes); |
78
|
|
|
|
79
|
|
|
return $middleware->process($request, $this); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|