Passed
Pull Request — master (#115)
by Alexander
02:48
created

RouteCollection::injectItem()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

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