Router::dispatch()   B
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 24
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 18
nc 6
nop 2
dl 0
loc 24
rs 8.5125
c 0
b 0
f 0
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
The expression return $route could return the type null which is incompatible with the type-hinted return WebComplete\mvc\router\Route. Consider adding an additional type-check to rule them out.
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