|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace Igni\Application\Http; |
|
4
|
|
|
|
|
5
|
|
|
use Igni\Network\Http\Router; |
|
6
|
|
|
use Igni\Network\Exception\RouterException; |
|
7
|
|
|
use Igni\Network\Http\Route; |
|
8
|
|
|
use Symfony\Component\Routing\Exception\MethodNotAllowedException as SymfonyMethodNotAllowedException; |
|
9
|
|
|
use Symfony\Component\Routing\Exception\ResourceNotFoundException; |
|
10
|
|
|
use Symfony\Component\Routing\Matcher\UrlMatcher; |
|
11
|
|
|
use Symfony\Component\Routing\RequestContext; |
|
12
|
|
|
use Symfony\Component\Routing\Route as SymfonyRoute; |
|
13
|
|
|
use Symfony\Component\Routing\RouteCollection; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* Wrapper for package symfony/router |
|
17
|
|
|
* |
|
18
|
|
|
* @package Igni\Http\Router |
|
19
|
|
|
*/ |
|
20
|
|
|
class GenericRouter implements Router |
|
21
|
|
|
{ |
|
22
|
|
|
/** @var RouteCollection */ |
|
23
|
|
|
protected $routeCollection; |
|
24
|
|
|
|
|
25
|
|
|
/** @var Route[] */ |
|
26
|
|
|
protected $routes = []; |
|
27
|
|
|
|
|
28
|
22 |
|
public function __construct() |
|
29
|
|
|
{ |
|
30
|
22 |
|
$this->routeCollection = new RouteCollection(); |
|
31
|
22 |
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* Registers new route. |
|
35
|
|
|
* |
|
36
|
|
|
* @param Route $route |
|
37
|
|
|
*/ |
|
38
|
15 |
|
public function add(Route $route): void |
|
39
|
|
|
{ |
|
40
|
15 |
|
if ($route instanceof Route) { |
|
|
|
|
|
|
41
|
15 |
|
$name = $route->getName(); |
|
42
|
|
|
} else { |
|
43
|
|
|
$name = Route::generateNameFromPath($route->getPath()); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
15 |
|
$baseRoute = new SymfonyRoute($route->getPath()); |
|
47
|
15 |
|
$baseRoute->setMethods($route->getMethods()); |
|
48
|
|
|
|
|
49
|
15 |
|
$this->routeCollection->add($name, $baseRoute); |
|
50
|
15 |
|
$this->routes[$name] = $route; |
|
51
|
15 |
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* Finds route matching clients request. |
|
55
|
|
|
* |
|
56
|
|
|
* @param string $method request method. |
|
57
|
|
|
* @param string $path request path. |
|
58
|
|
|
* @return Route |
|
59
|
|
|
*/ |
|
60
|
17 |
|
public function find(string $method, string $path): Route |
|
61
|
|
|
{ |
|
62
|
17 |
|
$matcher = new UrlMatcher($this->routeCollection, new RequestContext('/', $method)); |
|
63
|
|
|
try { |
|
64
|
17 |
|
$route = $matcher->match($path); |
|
65
|
5 |
|
} catch (ResourceNotFoundException $exception) { |
|
66
|
4 |
|
throw RouterException::noRouteMatchesRequestedUri($path, $method); |
|
67
|
1 |
|
} catch (SymfonyMethodNotAllowedException $exception) { |
|
68
|
1 |
|
throw RouterException::methodNotAllowed($path, $exception->getAllowedMethods()); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
12 |
|
$routeName = $route['_route']; |
|
72
|
12 |
|
unset($route['_route']); |
|
73
|
|
|
|
|
74
|
12 |
|
return $this->routes[$routeName]->withAttributes($route); |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|