Passed
Pull Request — master (#113)
by Rustam
02:54
created

RouteCollection::injectGroup()   C

Complexity

Conditions 13
Paths 41

Size

Total Lines 45
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 27
CRAP Score 13.0076

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 13
eloc 28
c 2
b 0
f 0
nc 41
nop 4
dl 0
loc 45
ccs 27
cts 28
cp 0.9643
crap 13.0076
rs 6.6166

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Router;
6
7
use InvalidArgumentException;
8
9
final class RouteCollection implements RouteCollectionInterface
10
{
11
    private RouteCollectorInterface $collector;
12
13
    private array $items = [];
14
15
    /**
16
     * All attached routes as Route instances
17
     *
18
     * @var Route[]
19
     */
20
    private array $routes = [];
21
22 8
    public function __construct(RouteCollectorInterface $collector)
23
    {
24 8
        $this->collector = $collector;
25 8
    }
26
27
    /**
28
     * @return Route[]
29
     */
30 1
    public function getRoutes(): array
31
    {
32 1
        $this->ensureItemsInjected();
33
        return $this->routes;
34
    }
35
36
    /**
37
     * @param string $name
38
     *
39
     * @return Route
40
     */
41 7
    public function getRoute(string $name): Route
42
    {
43 7
        $this->ensureItemsInjected();
44 7
        if (!array_key_exists($name, $this->routes)) {
45
            throw new RouteNotFoundException($name);
46
        }
47
48 7
        return $this->routes[$name];
49
    }
50
51
    /**
52
     * Returns routes tree array
53
     *
54
     * @param bool $routeAsString
55
     *
56
     * @return array
57
     */
58
    public function getRouteTree(bool $routeAsString = true): array
59
    {
60
        $this->ensureItemsInjected();
61
        return $this->buildTree($this->items, $routeAsString);
62
    }
63
64 8
    private function ensureItemsInjected(): void
65
    {
66 8
        if ($this->items === []) {
67 8
            $this->injectItems([$this->collector]);
68
        }
69 7
    }
70
71
    /**
72
     * Build routes array
73
     *
74
     * @param Group[]|Route[]|RouteCollectorInterface[] $items
75
     */
76 8
    private function injectItems(array $items): void
77
    {
78 8
        foreach ($items as $index => $item) {
79 8
            $this->injectItem($item);
80
        }
81 7
    }
82
83
    /**
84
     * Add an item into routes array
85
     *
86
     * @param Group|Route $route
87
     */
88 8
    private function injectItem($route): void
89
    {
90 8
        if ($route instanceof Group) {
91 8
            $this->injectGroup($route, $this->items);
92 7
            return;
93
        }
94
95
        $this->items[] = $route->getName();
96
        $routeName = $route->getName();
97
        if (isset($this->routes[$routeName]) && !$route->isOverride()) {
98
            throw new InvalidArgumentException("A route with name '$routeName' already exists.");
99
        }
100
        $this->routes[$routeName] = $route;
101
    }
102
103
    /**
104
     * Inject a Group instance into route and item arrays.
105
     */
106 8
    private function injectGroup(Group $group, array &$tree, string $prefix = '', string $namePrefix = ''): void
107
    {
108 8
        $prefix .= $group->getPrefix();
109 8
        $namePrefix .= $group->getName();
110 8
        $items = $group->getItems();
111 8
        foreach ($items as $item) {
112 8
            if ($item instanceof Group || $item->hasMiddlewares()) {
113 6
                $groupMiddlewares = $group->getMiddlewareDefinitions();
114 6
                foreach ($groupMiddlewares as $middleware) {
115 4
                    $item = $item->prependMiddleware($middleware);
116
                }
117
            }
118
119 8
            if ($group->getHost() !== null && $item->getHost() === null) {
120 1
                $item = $item->host($group->getHost());
121
            }
122
123 8
            if ($item instanceof Group) {
124 5
                if (empty($item->getPrefix())) {
125 1
                    $this->injectGroup($item, $tree, $prefix, $namePrefix);
126 1
                    continue;
127
                }
128 4
                $tree[$item->getPrefix()] = [];
129 4
                $this->injectGroup($item, $tree[$item->getPrefix()], $prefix, $namePrefix);
130 4
                continue;
131
            }
132
133
            /** @var Route $modifiedItem */
134 8
            $modifiedItem = $item->pattern($prefix . $item->getPattern());
135
136 8
            if (strpos($item->getName(), implode(', ', $item->getMethods())) === false) {
137 8
                $modifiedItem = $modifiedItem->name($namePrefix . $item->getName());
138
            }
139
140 8
            if (empty($tree[$group->getPrefix()])) {
141 8
                $tree[] = $modifiedItem->getName();
142
            } else {
143
                $tree[$group->getPrefix()][] = $modifiedItem->getName();
144
            }
145
146 8
            $routeName = $modifiedItem->getName();
147 8
            if (isset($this->routes[$routeName]) && !$modifiedItem->isOverride()) {
148 1
                throw new InvalidArgumentException("A route with name '$routeName' already exists.");
149
            }
150 8
            $this->routes[$routeName] = $modifiedItem;
151
        }
152 7
    }
153
154
    /**
155
     * Builds route tree from items
156
     *
157
     * @param array $items
158
     * @param bool $routeAsString
159
     *
160
     * @return array
161
     */
162
    private function buildTree(array $items, bool $routeAsString): array
163
    {
164
        $tree = [];
165
        foreach ($items as $key => $item) {
166
            if (is_array($item)) {
167
                $tree[$key] = $this->buildTree($items[$key], $routeAsString);
168
            } else {
169
                $tree[] = $routeAsString ? (string)$this->getRoute($item) : $this->getRoute($item);
170
            }
171
        }
172
        return $tree;
173
    }
174
}
175