Router::dispatch()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace DarkMatter\Components\Router;
6
7
use FastRoute;
8
use FastRoute\RouteCollector;
9
10
class Router implements RouterInterface
11
{
12
    /**
13
     * @var array $routes
14
     */
15
    protected $routes;
16
17
    /**
18
     * @var FastRoute\Dispatcher $routeDispatcher
19
     */
20
    protected $routeDispatcher;
21
22
    public function __construct(array $routes)
23
    {
24
        $this->routes = $routes;
25
        $this->bootstrapDispatcher();
26
    }
27
28
    /**
29
     * Prepares the route dispatcher.
30
     *
31
     * @return void
32
     */
33
    protected function bootstrapDispatcher(): void
34
    {
35
        $this->routeDispatcher = FastRoute\simpleDispatcher(function (RouteCollector $collector) {
36
            foreach ($this->routes as $routeName => $route) {
37
                $collector->addRoute($route['method'], $route['pattern'], $route['handler']);
38
            }
39
        });
40
    }
41
42
    /**
43
     * Dispatches HTTP request and returns route information.
44
     *
45
     * @param string $httpMethod
46
     * @param string $uri
47
     * @return array
48
     */
49
    public function dispatch(string $httpMethod, string $uri) : array
50
    {
51
        $urlPath = rawurldecode(parse_url($uri, PHP_URL_PATH));
52
        $routeInfo = $this->routeDispatcher->dispatch($httpMethod, $urlPath);
53
        return $routeInfo;
54
    }
55
}
56