web-complete /
mvc
| 1 | <?php |
||
| 2 | |||
| 3 | namespace WebComplete\mvc\router; |
||
| 4 | |||
| 5 | use FastRoute\Dispatcher; |
||
| 6 | use FastRoute\RouteCollector; |
||
| 7 | use WebComplete\mvc\router\exception\Exception; |
||
| 8 | use WebComplete\mvc\router\exception\NotAllowedException; |
||
| 9 | use WebComplete\mvc\router\exception\NotFoundException; |
||
| 10 | |||
| 11 | class Router |
||
| 12 | { |
||
| 13 | |||
| 14 | /** |
||
| 15 | * @var Routes |
||
| 16 | */ |
||
| 17 | private $config; |
||
| 18 | |||
| 19 | /** |
||
| 20 | * @param Routes $config |
||
| 21 | */ |
||
| 22 | public function __construct(Routes $config) |
||
| 23 | { |
||
| 24 | $this->config = $config; |
||
| 25 | } |
||
| 26 | |||
| 27 | /** |
||
| 28 | * @param string $method |
||
| 29 | * @param string $uri |
||
| 30 | * |
||
| 31 | * @return Route |
||
| 32 | * @throws \WebComplete\mvc\router\exception\Exception |
||
| 33 | * @throws \WebComplete\mvc\router\exception\NotAllowedException |
||
| 34 | * @throws \WebComplete\mvc\router\exception\NotFoundException |
||
| 35 | */ |
||
| 36 | public function dispatch(string $method, string $uri): Route |
||
| 37 | { |
||
| 38 | $route = null; |
||
| 39 | $dispatcher = $this->configureDispatcher(); |
||
| 40 | $routeInfo = $dispatcher->dispatch($method, $uri); |
||
| 41 | switch ($routeInfo[0]) { |
||
| 42 | case Dispatcher::NOT_FOUND: |
||
| 43 | throw new NotFoundException('Route not found'); |
||
| 44 | break; |
||
| 45 | case Dispatcher::METHOD_NOT_ALLOWED: |
||
| 46 | throw new NotAllowedException('Route not allowed'); |
||
| 47 | break; |
||
| 48 | case Dispatcher::FOUND: |
||
| 49 | if (!isset($routeInfo[1][0])) { |
||
| 50 | throw new Exception('Controller class name expected'); |
||
| 51 | } |
||
| 52 | if (!isset($routeInfo[1][1])) { |
||
| 53 | throw new Exception('Action method name expected'); |
||
| 54 | } |
||
| 55 | $route = new Route($routeInfo[1][0], $routeInfo[1][1], $routeInfo[2]); |
||
| 56 | break; |
||
| 57 | } |
||
| 58 | |||
| 59 | return $route; |
||
|
0 ignored issues
–
show
Bug
Best Practice
introduced
by
Loading history...
|
|||
| 60 | } |
||
| 61 | |||
| 62 | /** |
||
| 63 | * @return Dispatcher |
||
| 64 | */ |
||
| 65 | protected function configureDispatcher(): Dispatcher |
||
| 66 | { |
||
| 67 | return \FastRoute\simpleDispatcher(function (RouteCollector $collector) { |
||
| 68 | foreach ($this->config as $route) { |
||
| 69 | $collector->addRoute($route[0], $route[1], $route[2]); |
||
| 70 | } |
||
| 71 | }); |
||
| 72 | } |
||
| 73 | } |
||
| 74 |