Completed
Push — master ( 495169...b31514 )
by Changwan
10:11
created

CompiledRouteCollection::dispatch()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 26
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 20
nc 8
nop 3
dl 0
loc 26
ccs 17
cts 17
cp 1
crap 5
rs 8.439
c 0
b 0
f 0
1
<?php
2
namespace Wandu\Router;
3
4
use FastRoute\Dispatcher as FastDispatcher;
5
use FastRoute\Dispatcher\GroupCountBased as GCBDispatcher;
6
use Psr\Http\Message\ServerRequestInterface;
7
use Wandu\Router\Contracts\Dispatchable;
8
use Wandu\Router\Contracts\LoaderInterface;
9
use Wandu\Router\Contracts\ResponsifierInterface;
10
use Wandu\Router\Exception\MethodNotAllowedException;
11
use Wandu\Router\Exception\RouteNotFoundException;
12
13
class CompiledRouteCollection implements Dispatchable
14
{
15
    /** @var \Wandu\Router\Route[] */
16
    protected $routeMap = [];
17
18
    /** @var array */
19
    protected $compiledRoutes = [];
20
21
    /**
22
     * @param array $compiledRoutes
23
     * @param array $routeMap
24
     */
25 14
    public function __construct(array $compiledRoutes, array $routeMap)
26
    {
27 14
        $this->routeMap = $routeMap;
28 14
        $this->compiledRoutes = $compiledRoutes;
29 14
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34 14
    public function dispatch(
35
        LoaderInterface $loader,
36
        ResponsifierInterface $responsifier,
37
        ServerRequestInterface $request
38
    ) {
39 14
        $host = $request->getHeaderLine('host');
40 14
        $compiledRoutes = array_key_exists($host, $this->compiledRoutes)
41 1
            ? $this->compiledRoutes[$host]
42 14
            : $this->compiledRoutes['@'];
43
        
44 14
        $routeInfo = (new GCBDispatcher($compiledRoutes))
45 14
            ->dispatch($request->getMethod(), '/' . trim($request->getUri()->getPath(), '/'));
46
        
47 14
        switch ($routeInfo[0]) {
48 14
            case FastDispatcher::NOT_FOUND:
49 4
                throw new RouteNotFoundException();
50 14
            case FastDispatcher::METHOD_NOT_ALLOWED:
51 8
                throw new MethodNotAllowedException();
52
        }
53 14
        $route = $this->routeMap[$routeInfo[1]];
54 14
        foreach ($routeInfo[2] as $key => $value) {
55 5
            $request = $request->withAttribute($key, $value);
56
        }
57 14
        $executor = new RouteExecutor($loader, $responsifier);
58 14
        return $executor->execute($route, $request);
59
    }
60
}
61