Passed
Pull Request — master (#222)
by Sergei
03:58 queued 25s
created

Route::defaults()   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 2
Bugs 0 Features 0
Metric Value
eloc 3
c 2
b 0
f 0
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Router;
6
7
use InvalidArgumentException;
8
use RuntimeException;
9
use Stringable;
10
use Yiisoft\Http\Method;
11
12
use function in_array;
13
14
/**
15
 * Route defines a mapping from URL to callback / name and vice versa.
16
 */
17
final class Route implements Stringable
18
{
19
    private ?string $name = null;
20
21
    /**
22
     * @var string[]
23
     */
24
    private array $hosts = [];
25
    private bool $override = false;
26
    private bool $actionAdded = false;
27
28
    /**
29
     * @var array[]|callable[]|string[]
30
     * @psalm-var list<array|callable|string>
31
     */
32
    private array $middlewares = [];
33
34
    private array $disabledMiddlewares = [];
35
36
    /**
37
     * @psalm-var list<array|callable|string>|null
38
     */
39
    private ?array $enabledMiddlewares = null;
40
41
    /**
42
     * @var array<string,string>
43
     */
44
    private array $defaults = [];
45
46
    /**
47
     * @param string[] $methods
48
     */
49 81
    private function __construct(
50
        private array $methods,
51
        private string $pattern,
52
    ) {
53 81
    }
54
55 69
    public static function get(string $pattern): self
56
    {
57 69
        return self::methods([Method::GET], $pattern);
58
    }
59
60 9
    public static function post(string $pattern): self
61
    {
62 9
        return self::methods([Method::POST], $pattern);
63
    }
64
65 4
    public static function put(string $pattern): self
66
    {
67 4
        return self::methods([Method::PUT], $pattern);
68
    }
69
70 1
    public static function delete(string $pattern): self
71
    {
72 1
        return self::methods([Method::DELETE], $pattern);
73
    }
74
75 1
    public static function patch(string $pattern): self
76
    {
77 1
        return self::methods([Method::PATCH], $pattern);
78
    }
79
80 1
    public static function head(string $pattern): self
81
    {
82 1
        return self::methods([Method::HEAD], $pattern);
83
    }
84
85 9
    public static function options(string $pattern): self
86
    {
87 9
        return self::methods([Method::OPTIONS], $pattern);
88
    }
89
90
    /**
91
     * @param string[] $methods
92
     */
93 81
    public static function methods(array $methods, string $pattern): self
94
    {
95 81
        return new self($methods, $pattern);
96
    }
97
98 23
    public function name(string $name): self
99
    {
100 23
        $route = clone $this;
101 23
        $route->name = $name;
102 23
        return $route;
103
    }
104
105 24
    public function pattern(string $pattern): self
106
    {
107 24
        $new = clone $this;
108 24
        $new->pattern = $pattern;
109 24
        return $new;
110
    }
111
112 9
    public function host(string $host): self
113
    {
114 9
        return $this->hosts($host);
115
    }
116
117 13
    public function hosts(string ...$hosts): self
118
    {
119 13
        $route = clone $this;
120 13
        $route->hosts = [];
121
122 13
        foreach ($hosts as $host) {
123 13
            $host = rtrim($host, '/');
124
125 13
            if ($host !== '' && !in_array($host, $route->hosts, true)) {
126 12
                $route->hosts[] = $host;
127
            }
128
        }
129
130 13
        return $route;
131
    }
132
133
    /**
134
     * Marks route as override. When added it will replace existing route with the same name.
135
     */
136 4
    public function override(): self
137
    {
138 4
        $route = clone $this;
139 4
        $route->override = true;
140 4
        return $route;
141
    }
142
143
    /**
144
     * Parameter default values indexed by parameter names.
145
     *
146
     * @psalm-param array<string,null|Stringable|scalar> $defaults
147
     */
148 3
    public function defaults(array $defaults): self
149
    {
150 3
        $route = clone $this;
151 3
        $route->defaults = array_map('\strval', $defaults);
152 3
        return $route;
153
    }
154
155
    /**
156
     * Appends a handler middleware definition that should be invoked for a matched route.
157
     * First added handler will be executed first.
158
     */
159 23
    public function middleware(array|callable|string ...$definition): self
160
    {
161 23
        if ($this->actionAdded) {
162 1
            throw new RuntimeException('middleware() can not be used after action().');
163
        }
164 22
        $route = clone $this;
165 22
        array_push(
166 22
            $route->middlewares,
167 22
            ...array_values($definition)
168 22
        );
169 22
        return $route;
170
    }
171
172
    /**
173
     * Prepends a handler middleware definition that should be invoked for a matched route.
174
     * Last added handler will be executed first.
175
     */
176 24
    public function prependMiddleware(array|callable|string ...$definition): self
177
    {
178 24
        if (!$this->actionAdded) {
179 1
            throw new RuntimeException('prependMiddleware() can not be used before action().');
180
        }
181 23
        $route = clone $this;
182 23
        array_unshift(
183 23
            $route->middlewares,
184 23
            ...array_values($definition)
185 23
        );
186 23
        return $route;
187
    }
188
189
    /**
190
     * Appends action handler. It is a primary middleware definition that should be invoked last for a matched route.
191
     */
192 27
    public function action(array|callable|string $middlewareDefinition): self
193
    {
194 27
        $route = clone $this;
195 27
        $route->middlewares[] = $middlewareDefinition;
196 27
        $route->actionAdded = true;
197 27
        return $route;
198
    }
199
200
    /**
201
     * Excludes middleware from being invoked when action is handled.
202
     * It is useful to avoid invoking one of the parent group middleware for
203
     * a certain route.
204
     */
205 4
    public function disableMiddleware(mixed ...$definition): self
206
    {
207 4
        $route = clone $this;
208 4
        array_push(
209 4
            $route->disabledMiddlewares,
210 4
            ...array_values($definition)
211 4
        );
212 4
        return $route;
213
    }
214
215
    /**
216
     * @psalm-template T as string
217
     *
218
     * @psalm-param T $key
219
     *
220
     * @psalm-return (
221
     *   T is ('name'|'pattern') ? string :
222
     *       (T is 'host' ? string|null :
223
     *           (T is 'hosts' ? array<array-key, string> :
224
     *               (T is 'methods' ? array<array-key,string> :
225
     *                   (T is 'defaults' ? array<string,string> :
226
     *                       (T is ('override'|'hasMiddlewares') ? bool :
227
     *                           (T is 'enabledMiddlewares' ? array<array-key,array|callable|string> : mixed)
228
     *                       )
229
     *                   )
230
     *               )
231
     *           )
232
     *       )
233
     *    )
234
     */
235 59
    public function getData(string $key): mixed
236
    {
237 59
        return match ($key) {
238 59
            'name' => $this->name ??
239 32
                (implode(', ', $this->methods) . ' ' . implode('|', $this->hosts) . $this->pattern),
240 59
            'pattern' => $this->pattern,
241 59
            'host' => $this->hosts[0] ?? null,
242 59
            'hosts' => $this->hosts,
243 59
            'methods' => $this->methods,
244 59
            'defaults' => $this->defaults,
245 59
            'override' => $this->override,
246 59
            'hasMiddlewares' => $this->middlewares !== [],
247 59
            'enabledMiddlewares' => $this->getEnabledMiddlewares(),
248 59
            default => throw new InvalidArgumentException('Unknown data key: ' . $key),
249 59
        };
250
    }
251
252 5
    public function __toString(): string
253
    {
254 5
        $result = $this->name === null
255 2
            ? ''
256 3
            : '[' . $this->name . '] ';
257
258 5
        if ($this->methods !== []) {
259 5
            $result .= implode(',', $this->methods) . ' ';
260
        }
261
262 5
        if ($this->hosts) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->hosts of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
263 2
            $quoted = array_map(static fn ($host) => preg_quote($host, '/'), $this->hosts);
264
265 2
            if (!preg_match('/' . implode('|', $quoted) . '/', $this->pattern)) {
266 2
                $result .= implode('|', $this->hosts);
267
            }
268
        }
269
270 5
        $result .= $this->pattern;
271
272 5
        return $result;
273
    }
274
275 1
    public function __debugInfo()
276
    {
277 1
        return [
278 1
            'name' => $this->name,
279 1
            'methods' => $this->methods,
280 1
            'pattern' => $this->pattern,
281 1
            'hosts' => $this->hosts,
282 1
            'defaults' => $this->defaults,
283 1
            'override' => $this->override,
284 1
            'actionAdded' => $this->actionAdded,
285 1
            'middlewares' => $this->middlewares,
286 1
            'disabledMiddlewares' => $this->disabledMiddlewares,
287 1
            'enabledMiddlewares' => $this->getEnabledMiddlewares(),
288 1
        ];
289
    }
290
291
    /**
292
     * @return array[]|callable[]|string[]
293
     * @psalm-return list<array|callable|string>
294
     */
295 22
    private function getEnabledMiddlewares(): array
296
    {
297 22
        if ($this->enabledMiddlewares !== null) {
298
            return $this->enabledMiddlewares;
299
        }
300
301 22
        $this->enabledMiddlewares = array_values(
302 22
            array_filter(
303 22
                $this->middlewares,
304 22
                fn ($definition) => !in_array($definition, $this->disabledMiddlewares, true)
305 22
            )
306 22
        );
307
308 22
        return $this->enabledMiddlewares;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->enabledMiddlewares returns the type null which is incompatible with the type-hinted return array.
Loading history...
309
    }
310
}
311