Router   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 2
dl 0
loc 46
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A bootstrapDispatcher() 0 8 2
A dispatch() 0 6 1
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