1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace N1215\Hakudo; |
5
|
|
|
|
6
|
|
|
use N1215\Http\RequestMatcher\RequestMatcherInterface; |
7
|
|
|
use N1215\Http\Router\Exception\RouteNotFoundException; |
8
|
|
|
use N1215\Http\Router\Result\RoutingResultFactory; |
9
|
|
|
use N1215\Http\Router\RouterInterface; |
10
|
|
|
use N1215\Http\Router\RoutingError; |
11
|
|
|
use N1215\Http\Router\RoutingResult; |
12
|
|
|
use N1215\Http\Router\RoutingResultFactoryInterface; |
13
|
|
|
use N1215\Http\Router\RoutingResultInterface; |
14
|
|
|
use N1215\Jugoya\RequestHandlerBuilderInterface; |
15
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
16
|
|
|
|
17
|
|
|
class Router implements RouterInterface |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* @var Route[] |
21
|
|
|
*/ |
22
|
|
|
private $routes; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var RequestHandlerBuilderInterface |
26
|
|
|
*/ |
27
|
|
|
private $builder; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @var RoutingResultFactory |
31
|
|
|
*/ |
32
|
|
|
private $resultFactory; |
33
|
|
|
|
34
|
2 |
|
public function __construct(RequestHandlerBuilderInterface $builder, RoutingResultFactory $resultFactory) |
35
|
|
|
{ |
36
|
2 |
|
$this->builder = $builder; |
37
|
2 |
|
$this->resultFactory = $resultFactory; |
38
|
2 |
|
$this->routes = []; |
39
|
2 |
|
} |
40
|
|
|
|
41
|
2 |
|
private function addRoute(Route $route): Route |
42
|
|
|
{ |
43
|
2 |
|
$this->routes[] = $route; |
44
|
2 |
|
return $route; |
45
|
|
|
} |
46
|
|
|
|
47
|
2 |
|
public function add(RequestMatcherInterface $matcher, $coreHandlerRef, array $middlewareRefs = []): Route |
48
|
|
|
{ |
49
|
2 |
|
$handler = $this->builder->build($coreHandlerRef, $middlewareRefs); |
50
|
2 |
|
return $this->addRoute(new Route($matcher, $handler)); |
51
|
|
|
} |
52
|
|
|
|
53
|
2 |
|
public function match(ServerRequestInterface $request): RoutingResultInterface |
54
|
|
|
{ |
55
|
2 |
|
foreach ($this->routes as $route) { |
56
|
|
|
|
57
|
2 |
|
$requestMatchResult = $route->match($request); |
58
|
|
|
|
59
|
2 |
|
if ($requestMatchResult->isSuccess()) { |
60
|
1 |
|
return $this->resultFactory->make( |
61
|
1 |
|
$route->getHandler(), |
62
|
2 |
|
$requestMatchResult->getParams() |
63
|
|
|
); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|
67
|
1 |
|
throw new RouteNotFoundException('route not found'); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|