Test Failed
Push — master ( 614e1a...5c1cf2 )
by gt9000
13:11
created

RouteDispatcher   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B dispatch() 0 37 5
1
<?php
2
3
namespace zqhong\route;
4
5
use zqhong\route\Helpers\Arr;
6
7
class RouteDispatcher
8
{
9
    /**
10
     * @var RouteCollector
11
     */
12
    protected $routeCollector;
13
14
    /**
15
     * RouteDispatcher constructor.
16
     * @param RouteCollector $routeCollector
17
     */
18
    public function __construct(RouteCollector $routeCollector)
19
    {
20
        $this->routeCollector = $routeCollector;
21
    }
22
23
    /**
24
     * @param string $httpMethod
25
     * @param string $uri
26
     * @return array
27
     */
28
    public function dispatch($httpMethod, $uri)
29
    {
30
        $return = [
31
            'isFound' => false,
32
            'handler' => '',
33
            'params' => [],
34
        ];
35
        $staticRoutes = $this->routeCollector->getStaticRoutes();
36
37
        if (isset($staticRoutes[$httpMethod][$uri])) {
38
            $return['isFound'] = true;
39
            $return['handler'] = $staticRoutes[$httpMethod][$uri];
40
        } else {
41
            $combinedVarRoutes = $this->routeCollector->getCombinedVarRoutes($httpMethod);
42
            if (!empty($combinedVarRoutes)) {
43
                $regex = Arr::getValue($combinedVarRoutes, 'regex');
44
                $routeMap = Arr::getValue($combinedVarRoutes, 'routeMap');
45
                preg_match($regex, $uri, $matches, $matches);
46
47
                $cnt = count($matches);
48
                if (isset($routeMap[$cnt])) {
49
                    $handler = $routeMap[$cnt]['handler'];
50
                    $params = $routeMap[$cnt]['params'];
51
52
                    foreach ($params as $k => $v) {
53
                        $params[$k] = $matches[--$cnt];
54
                    }
55
56
                    $return['isFound'] = true;
57
                    $return['handler'] = $handler;
58
                    $return['params'] = $params;
59
                }
60
            }
61
        }
62
63
        return $return;
64
    }
65
}
66