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