Passed
Push — master ( 0f979d...0862ec )
by Hong
02:33 queued 13s
created

RouteGroup   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 77
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 30
c 1
b 0
f 0
dl 0
loc 77
rs 10
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A match() 0 29 3
A addRoute() 0 14 2
1
<?php
2
3
/**
4
 * Phoole (PHP7.2+)
5
 *
6
 * @category  Library
7
 * @package   Phoole\Route
8
 * @copyright Copyright (c) 2019 Hong Zhang
9
 */
10
declare(strict_types=1);
11
12
namespace Phoole\Route\Util;
13
14
use Phoole\Route\Router;
15
use Phoole\Route\Parser\ParserInterface;
16
17
/**
18
 * RouteGroup
19
 *
20
 * @package Phoole\Route
21
 */
22
class RouteGroup
23
{
24
    /**
25
     * @var Route[]
26
     */
27
    protected $routes = [];
28
29
    /**
30
     * @var ParserInterface
31
     */
32
    protected $parser;
33
34
    /**
35
     * Set the parser
36
     *
37
     * @param  ParserInterface $parser
38
     */
39
    public function __construct(ParserInterface $parser)
40
    {
41
        $this->parser = $parser;
42
    }
43
44
    /**
45
     * Add a route to the route group
46
     *
47
     * @param  Route $route
48
     * @return RouteGroup $this
49
     */
50
    public function addRoute(Route $route): RouteGroup
51
    {
52
        $pattern = $route->getPattern();
53
        $hash = md5($route->getPattern());
54
55
        if (isset($this->routes[$hash])) {
56
            // add new method to existing route
57
            $this->routes[$hash]->addMethods($route);
58
        } else {
59
            // add new route
60
            $this->routes[$hash] = $route;
61
        }
62
        $this->parser->parse($hash, $pattern);
63
        return $this;
64
    }
65
66
    /**
67
     * @param  Result
68
     * @return bool
69
     */
70
    public function match(Result $result): bool
71
    {
72
        $request = $result->getRequest();
73
        $uri = $request->getUri()->getPath();
74
        $mth = $request->getMethod();
75
76
        $res = $this->parser->match($uri);
77
78
        if (empty($res)) {
79
            return false;
80
        }
81
82
        list($hash, $params) = $res;
83
        $route = $this->routes[$hash];
84
        if (isset($route->getMethods()[$mth])) {
85
            list($handler, $defaults) = $route->getMethods()[$mth];
86
87
            $request = $request->withAttribute(
88
                Router::URI_PARAMETERS,
89
                array_merge($defaults, $params)
90
            );
91
92
            $result->setHandler($handler);
93
            $result->setRoute($route);
94
            $result->setRequest($request);
95
            return true;
96
        }
97
98
        return false;
99
    }
100
}
101