Passed
Push — develop ( 429d81...1647ec )
by Brent
02:48
created

Router::get()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 2
dl 0
loc 6
ccs 3
cts 3
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Stitcher\Application;
4
5
use FastRoute\Dispatcher;
6
use FastRoute\Dispatcher\GroupCountBased;
7
use FastRoute\RouteCollector;
8
use GuzzleHttp\Psr7\Request;
9
use GuzzleHttp\Psr7\Response;
10
use Stitcher\App;
11
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
12
13
class Router
14
{
15
    protected $routeCollector;
16
17 4
    public function __construct(RouteCollector $routeCollector)
18
    {
19 4
        $this->routeCollector = $routeCollector;
20 4
    }
21
22 2
    public function get(string $url, string $controller): Router
23
    {
24 2
        $this->routeCollector->addRoute('GET', $url, [$controller, 'handle']);
25
26 2
        return $this;
27
    }
28
29
    public function post(string $url, string $controller): Router
30
    {
31
        $this->routeCollector->addRoute('POST', $url, [$controller, 'handle']);
32
33
        return $this;
34
    }
35
36 1
    public function dispatch(Request $request): ?Response
37
    {
38 1
        $dispatcher = new GroupCountBased($this->routeCollector->getData());
39
40 1
        $routeInfo = $dispatcher->dispatch($request->getMethod(), $request->getUri()->getPath());
41
42 1
        if ($routeInfo[0] !== Dispatcher::FOUND) {
43
            return null;
44
        }
45
46 1
        $handler = $this->resolveHandler($routeInfo[1]);
47 1
        $parameters = $routeInfo[2];
48
49 1
        return call_user_func_array(
50 1
            $handler,
51 1
            array_merge($parameters, [$request])
52
        );
53
    }
54
55 1
    protected function resolveHandler(array $callback): array
56
    {
57 1
        $className = $callback[0];
58
59
        try {
60 1
            $handler = App::get($className);
61 1
        } catch (ServiceNotFoundException $e) {
62 1
            $handler = new $className();
63
        }
64
65 1
        $callback[0] = $handler;
66
67 1
        return $callback;
68
    }
69
}
70