Passed
Pull Request — master (#134)
by Rustam
02:33
created

RouteCollection::getRoute()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

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