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

Group::namePrefix()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Router;
6
7
use InvalidArgumentException;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Psr\Http\Server\RequestHandlerInterface;
10
use RuntimeException;
11
use Yiisoft\Http\Method;
12
use Yiisoft\Middleware\Dispatcher\MiddlewareDispatcher;
13
14
use function get_class;
15
use function in_array;
16
use function is_object;
17
18
final class Group implements GroupInterface
19
{
20
    /**
21
     * @var Group[]|Route[]
22
     */
23
    private array $items = [];
24
    private ?string $prefix;
25
    private array $middlewareDefinitions = [];
26
    private ?string $host = null;
27
    private ?string $namePrefix = null;
28
    private bool $routesAdded = false;
29
    private bool $middlewareAdded = false;
30
    private array $disabledMiddlewareDefinitions = [];
31
    private ?MiddlewareDispatcher $dispatcher;
32
33 23
    private function __construct(?string $prefix = null, MiddlewareDispatcher $dispatcher = null)
34
    {
35 23
        $this->dispatcher = $dispatcher;
36 23
        $this->prefix = $prefix;
37 23
    }
38
39
    /**
40
     * Create a new group instance.
41
     *
42
     * @param string|null $prefix URL prefix to prepend to all routes of the group.
43
     * @param MiddlewareDispatcher|null $dispatcher Middleware dispatcher to use for the group.
44
     *
45
     * @return GroupInterface
46
     */
47 23
    public static function create(
48
        ?string $prefix = null,
49
        MiddlewareDispatcher $dispatcher = null
50
    ): GroupInterface {
51 23
        return new self($prefix, $dispatcher);
52
    }
53
54 20
    public function routes(...$routes): GroupInterface
55
    {
56 20
        if ($this->middlewareAdded) {
57 1
            throw new RuntimeException('routes() can not be used after prependMiddleware().');
58
        }
59 19
        $new = clone $this;
60 19
        foreach ($routes as $route) {
61 19
            if ($route instanceof Route || $route instanceof self) {
62 18
                if (!$route->hasDispatcher() && $new->hasDispatcher()) {
63 5
                    $route = $route->withDispatcher($new->dispatcher);
64
                }
65 18
                $new->items[] = $route;
66
            } else {
67 1
                $type = is_object($route) ? get_class($route) : gettype($route);
68 1
                throw new InvalidArgumentException(
69 1
                    sprintf('Route should be either an instance of Route or Group, %s given.', $type)
70
                );
71
            }
72
        }
73
74 18
        $new->routesAdded = true;
75
76 18
        return $new;
77
    }
78
79 2
    public function withDispatcher(MiddlewareDispatcher $dispatcher): GroupInterface
80
    {
81 2
        $group = clone $this;
82 2
        $group->dispatcher = $dispatcher;
83 2
        foreach ($group->items as $index => $item) {
84 2
            if (!$item->hasDispatcher()) {
85 2
                $item = $item->withDispatcher($dispatcher);
86 2
                $group->items[$index] = $item;
87
            }
88
        }
89
90 2
        return $group;
91
    }
92
93 2
    public function withAutoOptions(...$middlewares): GroupInterface
94
    {
95 2
        if (!$this->routesAdded) {
96
            throw new RuntimeException('withAutoOptions() can not be used before routes().');
97
        }
98 2
        $group = clone $this;
99 2
        $pattern = null;
100 2
        foreach ($group->items as $index => $item) {
101 2
            if ($item instanceof self) {
102 1
                $item = $item->withAutoOptions(...$middlewares);
103 1
                $group->items[$index] = $item;
104
            } else {
105
                // Avoid duplicates
106 2
                if ($pattern === $item->getPattern() || in_array(Method::OPTIONS, $item->getMethods(), true)) {
107 2
                    continue;
108
                }
109 2
                $pattern = $item->getPattern();
110 2
                $route = Route::options($pattern);
111 2
                foreach ($middlewares as $middleware) {
112 2
                    $route = $route->middleware($middleware);
113
                }
114 2
                $group->items[] = $route->action(
115 2
                    static fn (ServerRequestInterface $request, RequestHandlerInterface $handler) => $handler->handle(
116
                        $request
117
                    )
118 2
                );
119
            }
120
        }
121
122 2
        return $group;
123
    }
124
125 18
    public function hasDispatcher(): bool
126
    {
127 18
        return $this->dispatcher !== null;
128
    }
129
130 7
    public function middleware($middlewareDefinition): GroupInterface
131
    {
132 7
        if ($this->routesAdded) {
133
            throw new RuntimeException('middleware() can not be used after routes().');
134
        }
135 7
        $new = clone $this;
136 7
        array_unshift($new->middlewareDefinitions, $middlewareDefinition);
137 7
        return $new;
138
    }
139
140 3
    public function prependMiddleware($middlewareDefinition): GroupInterface
141
    {
142 3
        $new = clone $this;
143 3
        $new->middlewareDefinitions[] = $middlewareDefinition;
144 3
        $new->middlewareAdded = true;
145 3
        return $new;
146
    }
147
148 3
    public function namePrefix(string $namePrefix): GroupInterface
149
    {
150 3
        $new = clone $this;
151 3
        $new->namePrefix = $namePrefix;
152 3
        return $new;
153
    }
154
155 2
    public function host(string $host): GroupInterface
156
    {
157 2
        $new = clone $this;
158 2
        $new->host = rtrim($host, '/');
159 2
        return $new;
160
    }
161
162
    public function disableMiddleware($middlewareDefinition): GroupInterface
163
    {
164
        $new = clone $this;
165
        $new->disabledMiddlewareDefinitions[] = $middlewareDefinition;
166
        return $new;
167
    }
168
169
    /**
170
     * @return Group[]|Route[]
171
     */
172 17
    public function getItems(): array
173
    {
174 17
        return $this->items;
175
    }
176
177 15
    public function getPrefix(): ?string
178
    {
179 15
        return $this->prefix;
180
    }
181
182 15
    public function getNamePrefix(): ?string
183
    {
184 15
        return $this->namePrefix;
185
    }
186
187 15
    public function getHost(): ?string
188
    {
189 15
        return $this->host;
190
    }
191
192 12
    public function getMiddlewareDefinitions(): array
193
    {
194 12
        foreach ($this->middlewareDefinitions as $index => $definition) {
195 8
            if (in_array($definition, $this->disabledMiddlewareDefinitions, true)) {
196
                unset($this->middlewareDefinitions[$index]);
197
            }
198
        }
199
200 12
        return $this->middlewareDefinitions;
201
    }
202
}
203