|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* It's free open-source software released under the MIT License. |
|
5
|
|
|
* |
|
6
|
|
|
* @author Anatoly Fenric <[email protected]> |
|
7
|
|
|
* @copyright Copyright (c) 2018, Anatoly Fenric |
|
8
|
|
|
* @license https://github.com/sunrise-php/http-router/blob/master/LICENSE |
|
9
|
|
|
* @link https://github.com/sunrise-php/http-router |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace Sunrise\Http\Router; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* Import classes |
|
16
|
|
|
*/ |
|
17
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
18
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
19
|
|
|
use Sunrise\Http\Router\Exception\MethodNotAllowedException; |
|
20
|
|
|
use Sunrise\Http\Router\Exception\PageNotFoundException; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* Router |
|
24
|
|
|
*/ |
|
25
|
|
|
class Router extends RouteCollection implements RouterInterface |
|
26
|
|
|
{ |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* {@inheritDoc} |
|
30
|
|
|
*/ |
|
31
|
|
|
public function match(ServerRequestInterface $request) : RouteInterface |
|
32
|
|
|
{ |
|
33
|
|
|
$allow = []; |
|
34
|
|
|
|
|
35
|
|
|
foreach ($this->getRoutes() as $route) |
|
36
|
|
|
{ |
|
37
|
|
|
$regex = route_regex($route->getPath(), $route->getPatterns()); |
|
38
|
|
|
|
|
39
|
|
|
if (\preg_match($regex, $request->getUri()->getPath(), $attributes)) |
|
40
|
|
|
{ |
|
41
|
|
|
$allow = \array_merge($allow, $route->getMethods()); |
|
42
|
|
|
|
|
43
|
|
|
if (\in_array($request->getMethod(), $route->getMethods())) |
|
44
|
|
|
{ |
|
45
|
|
|
return $route->withAttributes($attributes); |
|
46
|
|
|
} |
|
47
|
|
|
} |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
if (! empty($allow)) |
|
51
|
|
|
{ |
|
52
|
|
|
throw new MethodNotAllowedException($request, $allow); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
throw new PageNotFoundException($request); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* {@inheritDoc} |
|
60
|
|
|
*/ |
|
61
|
|
|
public function handle(ServerRequestInterface $request) : ResponseInterface |
|
62
|
|
|
{ |
|
63
|
|
|
$route = $this->match($request); |
|
64
|
|
|
|
|
65
|
|
|
foreach ($route->getAttributes() as $name => $value) |
|
66
|
|
|
{ |
|
67
|
|
|
$request = $request->withAttribute($name, $value); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
$request = $request->withAttribute('@route', $route->getId()); |
|
71
|
|
|
|
|
72
|
|
|
$requestHandler = new RequestHandler(); |
|
73
|
|
|
|
|
74
|
|
|
foreach ($this->getMiddlewareStack() as $middleware) |
|
75
|
|
|
{ |
|
76
|
|
|
$requestHandler->add($middleware); |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
|
|
foreach ($route->getMiddlewareStack() as $middleware) |
|
80
|
|
|
{ |
|
81
|
|
|
$requestHandler->add($middleware); |
|
82
|
|
|
} |
|
83
|
|
|
|
|
84
|
|
|
$requestHandler->add($route); |
|
85
|
|
|
|
|
86
|
|
|
return $requestHandler->handle($request); |
|
87
|
|
|
} |
|
88
|
|
|
} |
|
89
|
|
|
|