RouteDispatcher   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 100%

Importance

Changes 6
Bugs 1 Features 1
Metric Value
wmc 6
c 6
b 1
f 1
lcom 1
cbo 5
dl 0
loc 67
ccs 21
cts 21
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B dispatch() 0 24 3
A createDispatcher() 0 8 2
1
<?php
2
3
namespace Mosaic\Routing\Adapters\FastRoute;
4
5
use FastRoute\Dispatcher;
6
use FastRoute\RouteCollector;
7
use Mosaic\Routing\Dispatchers\Dispatcher as DispatcherInterface;
8
use Mosaic\Routing\Exceptions\MethodNotAllowedException;
9
use Mosaic\Routing\Exceptions\NotFoundHttpException;
10
use Mosaic\Routing\RouteCollection;
11
use Mosaic\Routing\RouteDispatcher as RouteDispatcherInterface;
12
use Psr\Http\Message\ServerRequestInterface;
13
14
class RouteDispatcher implements RouteDispatcherInterface
15
{
16
    /**
17
     * @var RouteCollection
18
     */
19
    private $collection;
20
21
    /**
22
     * @var DispatcherInterface
23
     */
24
    private $dispatcher;
25
26
    /**
27
     * @param DispatcherInterface $dispatcher
28
     * @param RouteCollection     $collection
29
     */
30 4
    public function __construct(DispatcherInterface $dispatcher, RouteCollection $collection)
31
    {
32 4
        $this->collection = $collection;
33 4
        $this->dispatcher = $dispatcher;
34 4
    }
35
36
    /**
37
     * Dispatch the request
38
     *
39
     * @param  ServerRequestInterface    $request
40
     * @throws MethodNotAllowedException
41
     * @throws NotFoundHttpException
42
     * @return mixed
43
     */
44 4
    public function dispatch(ServerRequestInterface $request)
45
    {
46 4
        $method = $request->getMethod();
47 4
        $uri    = $request->getUri()->getPath();
48
49 4
        $routeInfo = $this->createDispatcher()->dispatch($method, $uri);
50
51 4
        switch ($routeInfo[0]) {
52 4
            case Dispatcher::METHOD_NOT_ALLOWED:
53 1
                throw new MethodNotAllowedException($routeInfo[1]);
54
55 3
            case Dispatcher::FOUND:
56 2
                $route = $routeInfo[1];
57 2
                $route->bind($routeInfo[2]);
58 2
                break;
59
60
            default:
61 1
                throw new NotFoundHttpException;
62
        }
63
64
        return $this->dispatcher->dispatch($route, function ($response) {
65
            return $response;
66 2
        });
67
    }
68
69
    /**
70
     * @return Dispatcher
71
     */
72
    private function createDispatcher()
73
    {
74 4
        return \FastRoute\simpleDispatcher(function (RouteCollector $collector) {
75 4
            foreach ($this->collection as $route) {
76 3
                $collector->addRoute($route->methods(), $route->uri(), $route);
77
            }
78 4
        });
79
    }
80
}
81