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

CompiledRouteCollection   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 100%

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B dispatch() 0 26 5
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