Passed
Pull Request — master (#115)
by Rustam
02:24
created

RouteCollection::getRoute()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 8
ccs 4
cts 5
cp 0.8
crap 2.032
rs 10
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->getItems());
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
            foreach ($this->collector->getMiddlewareDefinitions() as $middlewareDefinition) {
80
                $item = $item->prependMiddleware($middlewareDefinition);
81
            }
82 8
            $this->injectItem($item);
83
        }
84 7
    }
85
86
    /**
87
     * Add an item into routes array
88
     *
89
     * @param Group|Route $route
90
     */
91 8
    private function injectItem($route): void
92
    {
93 8
        if ($route instanceof Group) {
94 8
            $this->injectGroup($route, $this->items);
95 7
            return;
96
        }
97
98
        $this->items[] = $route->getName();
99
        $routeName = $route->getName();
100
        if (isset($this->routes[$routeName]) && !$route->isOverride()) {
101
            throw new InvalidArgumentException("A route with name '$routeName' already exists.");
102
        }
103
        $this->routes[$routeName] = $route;
104
    }
105
106
    /**
107
     * Inject a Group instance into route and item arrays.
108
     */
109 8
    private function injectGroup(Group $group, array &$tree, string $prefix = '', string $namePrefix = ''): void
110
    {
111 8
        $prefix .= $group->getPrefix();
112 8
        $namePrefix .= $group->getNamePrefix();
113 8
        $items = $group->getItems();
114 8
        foreach ($items as $item) {
115 8
            if ($item instanceof Group || $item->hasMiddlewares()) {
116 6
                $groupMiddlewares = $group->getMiddlewareDefinitions();
117 6
                foreach ($groupMiddlewares as $middleware) {
118 4
                    $item = $item->prependMiddleware($middleware);
119
                }
120
            }
121
122 8
            if ($group->getHost() !== null && $item->getHost() === null) {
123 1
                $item = $item->host($group->getHost());
124
            }
125
126 8
            if ($item instanceof Group) {
127 3
                if (empty($item->getPrefix())) {
128 2
                    $this->injectGroup($item, $tree, $prefix, $namePrefix);
129 2
                    continue;
130
                }
131 2
                $tree[$item->getPrefix()] = [];
132 2
                $this->injectGroup($item, $tree[$item->getPrefix()], $prefix, $namePrefix);
133 2
                continue;
134
            }
135
136
            /** @var Route $modifiedItem */
137 8
            $modifiedItem = $item->pattern($prefix . $item->getPattern());
138
139 8
            if (strpos($modifiedItem->getName(), implode(', ', $modifiedItem->getMethods())) === false) {
140 8
                $modifiedItem = $modifiedItem->name($namePrefix . $modifiedItem->getName());
141
            }
142
143 8
            if (empty($tree[$group->getPrefix()])) {
144 8
                $tree[] = $modifiedItem->getName();
145
            } else {
146
                $tree[$group->getPrefix()][] = $modifiedItem->getName();
147
            }
148
149 8
            $routeName = $modifiedItem->getName();
150 8
            if (isset($this->routes[$routeName]) && !$modifiedItem->isOverride()) {
151 1
                throw new InvalidArgumentException("A route with name '$routeName' already exists.");
152
            }
153 8
            $this->routes[$routeName] = $modifiedItem;
154
        }
155 7
    }
156
157
    /**
158
     * Builds route tree from items
159
     *
160
     * @param array $items
161
     * @param bool $routeAsString
162
     *
163
     * @return array
164
     */
165
    private function buildTree(array $items, bool $routeAsString): array
166
    {
167
        $tree = [];
168
        foreach ($items as $key => $item) {
169
            if (is_array($item)) {
170
                $tree[$key] = $this->buildTree($items[$key], $routeAsString);
171
            } else {
172
                $tree[] = $routeAsString ? (string)$this->getRoute($item) : $this->getRoute($item);
173
            }
174
        }
175
        return $tree;
176
    }
177
}
178