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; |
12
|
|
|
|
13
|
|
|
use Psr\Http\Message\RequestInterface; |
14
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Interface RouterInterface |
18
|
|
|
* |
19
|
|
|
* @package CoiSA\Http |
20
|
|
|
*/ |
21
|
|
|
final class Router implements RouterInterface |
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* @var array |
25
|
|
|
*/ |
26
|
|
|
private $routes; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @var RequestHandlerInterface |
30
|
|
|
*/ |
31
|
|
|
private $notFoundHandler; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Router constructor. |
35
|
|
|
* |
36
|
|
|
* @param RequestHandlerInterface $notFoundHandler |
37
|
|
|
*/ |
38
|
|
|
public function __construct(RequestHandlerInterface $notFoundHandler) |
39
|
|
|
{ |
40
|
|
|
$this->notFoundHandler = $notFoundHandler; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param string $method |
45
|
|
|
* @param string $regex |
46
|
|
|
* @param RequestHandlerInterface $requestHandler |
47
|
|
|
*/ |
48
|
|
|
public function addRoute(string $method, string $regex, RequestHandlerInterface $requestHandler): void |
49
|
|
|
{ |
50
|
|
|
$this->routes[$method][$regex] = $requestHandler; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @param RequestInterface $request |
55
|
|
|
* |
56
|
|
|
* @return RouteMatchInterface |
57
|
|
|
*/ |
58
|
|
|
public function match(RequestInterface $request): RouteMatchInterface |
59
|
|
|
{ |
60
|
|
|
if (!isset($this->routes[$request->getMethod()])) { |
61
|
|
|
return new RouteMatch($this->notFoundHandler); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
foreach ($this->routes[$request->getMethod()] as $regex => $requestHandler) { |
65
|
|
|
if (!preg_match($regex, $request->getRequestTarget(), $matches)) { |
66
|
|
|
continue; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return new RouteMatch($requestHandler, $matches); |
70
|
|
|
} |
|
|
|
|
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|
For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example: