|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace Igni\Http; |
|
4
|
|
|
|
|
5
|
|
|
use Igni\Http\Exception\NotFoundException; |
|
6
|
|
|
use Symfony\Component\Routing\Exception\MethodNotAllowedException; |
|
7
|
|
|
use Symfony\Component\Routing\Exception\ResourceNotFoundException; |
|
8
|
|
|
use Symfony\Component\Routing\Matcher\UrlMatcher; |
|
9
|
|
|
use Symfony\Component\Routing\RequestContext; |
|
10
|
|
|
use Symfony\Component\Routing\RouteCollection; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* Utility class for simplifying api for nikic router. |
|
14
|
|
|
* |
|
15
|
|
|
* @package Igni\Http |
|
16
|
|
|
*/ |
|
17
|
|
|
class Router |
|
18
|
|
|
{ |
|
19
|
|
|
/** |
|
20
|
|
|
* @var RouteCollection |
|
21
|
|
|
*/ |
|
22
|
|
|
private $routeCollection; |
|
23
|
|
|
|
|
24
|
|
|
/** @var array */ |
|
25
|
|
|
private $routes = []; |
|
26
|
|
|
|
|
27
|
18 |
|
public function __construct() |
|
28
|
|
|
{ |
|
29
|
18 |
|
$this->routeCollection = new RouteCollection(); |
|
30
|
18 |
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* Registers new route. |
|
34
|
|
|
* |
|
35
|
|
|
* @param Route $route |
|
36
|
|
|
*/ |
|
37
|
13 |
|
public function addRoute(Route $route): void |
|
38
|
|
|
{ |
|
39
|
13 |
|
$baseRoute = $route->getBaseRoute(); |
|
40
|
13 |
|
$this->routeCollection->add($route->getName(), $baseRoute); |
|
41
|
13 |
|
$this->routes[$route->getName()] = $route; |
|
42
|
13 |
|
} |
|
43
|
|
|
|
|
44
|
|
|
/** |
|
45
|
|
|
* Finds route matching clients request. |
|
46
|
|
|
* |
|
47
|
|
|
* @param string $method request method. |
|
48
|
|
|
* @param string $path request path. |
|
49
|
|
|
* @return Route |
|
50
|
|
|
*/ |
|
51
|
14 |
|
public function findRoute(string $method, string $path): Route |
|
52
|
|
|
{ |
|
53
|
14 |
|
$matcher = new UrlMatcher($this->routeCollection, new RequestContext('/', $method)); |
|
54
|
|
|
try { |
|
55
|
14 |
|
$route = $matcher->match($path); |
|
56
|
4 |
|
} catch (ResourceNotFoundException $exception) { |
|
57
|
3 |
|
throw NotFoundException::notFound($path, $method); |
|
58
|
1 |
|
} catch (MethodNotAllowedException $exception) { |
|
59
|
1 |
|
throw \Igni\Http\Exception\MethodNotAllowedException::methodNotAllowed($path, $method, $exception->getAllowedMethods()); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
10 |
|
$routeName = $route['_route']; |
|
63
|
10 |
|
unset($route['_route']); |
|
64
|
|
|
|
|
65
|
10 |
|
return $this->routes[$routeName]->withAttributes($route); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|