Test Failed
Push — master ( c7a4a9...a67054 )
by Divine Niiquaye
02:34
created

Route::arguments()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 7
rs 10
ccs 0
cts 0
cp 0
cc 2
nc 2
nop 1
crap 6
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Flight Routing.
7
 *
8
 * PHP version 7.1 and above required
9
 *
10
 * @author    Divine Niiquaye Ibok <[email protected]>
11
 * @copyright 2019 Biurad Group (https://biurad.com/)
12
 * @license   https://opensource.org/licenses/BSD-3-Clause License
13
 *
14
 * For the full copyright and license information, please view the LICENSE
15
 * file that was distributed with this source code.
16
 */
17
18
namespace Flight\Routing;
19
20
/**
21
 * Value object representing a single route.
22
 *
23
 * Internally, only those three properties are required. However, underlying
24
 * router implementations may allow or require additional information, such as
25
 * information defining how to generate a URL from the given route, qualifiers
26
 * for how segments of a route match, or even default values to use.
27
 *
28
 * __call() forwards method-calls to Route, but returns mixed contents.
29
 * listing Route's methods below, so that IDEs know they are valid
30
 *
31
 * @method string getPath() Gets the route path.
32
 * @method null|string getName() Gets the route name.
33
 * @method string[] getMethods() Gets the route methods.
34
 * @method string[] getSchemes() Gets the route domain schemes.
35
 * @method string[] getDomain() Gets the route host.
36
 * @method mixed getController() Gets the route handler.
37
 * @method array getMiddlewares() Gets the route middlewares.
38
 * @method array getPatterns() Gets the route pattern placeholder assert.
39
 * @method array getDefaults() Gets the route default settings.
40
 * @method array getArguments() Gets the arguments passed to route handler as parameters.
41
 * @method array getAll() Gets all the routes properties.
42
 *
43
 * @author Divine Niiquaye Ibok <[email protected]>
44
 */
45
class Route
46
{
47
    use Traits\CastingTrait;
48
49
    /**
50
     * A Pattern to Locates appropriate route by name, support dynamic route allocation using following pattern:
51
     * Pattern route:   `pattern/*<controller@action>`
52
     * Default route: `*<controller@action>`
53
     * Only action:   `pattern/*<action>`.
54
     *
55
     * @var string
56
     */
57
    public const RCA_PATTERN = '/^(?P<route>.*?)?(?P<handler>\*\<(?:(?<c>[a-zA-Z0-9\\\\]+)\@)?(?<a>[a-zA-Z0-9_\-]+)\>)?$/u';
58
59
    /**
60
     * A Pattern to match protocol, host and port from a url
61
     *
62
     * Examples of urls that can be matched:
63
     * http://en.example.domain
64
     * //example.domain
65
     * //example.com
66
     * https://example.com:34
67
     * //example.com
68
     * example.com
69
     * localhost:8000
70
     * {foo}.domain.com
71
     *
72
     * Also supports api resource routing, eg: api://user/path
73
     *
74
     * @var string
75
     */
76
    public const URL_PATTERN = '/^(?:(?P<scheme>api|https?)\:)?(\/\/)?(?P<host>[^\/\*]+)\/*?$/u';
77
78
    /**
79 151
     * Create a new Route constructor.
80
     *
81 151
     * @param string $pattern The route pattern
82 151
     * @param string $methods The route HTTP methods. Multiple methods can be supplied,
83 151
     *                        delimited by a pipe character '|', eg. 'GET|POST'
84 151
     * @param mixed  $handler The PHP class, object or callable that returns the response when matched
85 150
     */
86
    public function __construct(string $pattern, string $methods = 'GET|HEAD', $handler = null)
87
    {
88
        $this->controller = $handler;
89
        $this->path       = $this->castRoute($pattern);
90
91
        if (!empty($methods)) {
92 1
            $this->method(...\explode('|', $methods));
93
        }
94 1
    }
95
96 1
    /**
97 1
     * @internal This is handled different by router
98 1
     *
99 1
     * @param array $properties
100 1
     *
101 1
     * @return self
102 1
     */
103
    public static function __set_state(array $properties)
104 1
    {
105
        $recovered = new self($properties['path'], '', $properties['controller']);
106
107
        unset($properties['path'], $properties['controller']);
108
109
        foreach ($properties as $name => $property) {
110
            $recovered->{$name} = $property;
111
        }
112
113
        return $recovered;
114
    }
115
116
    /**
117
     * @param string   $method
118
     * @param mixed[] $arguments
119
     *
120
     * @return mixed
121
     */
122
    public function __call($method, $arguments)
123
    {
124
        $routeMethod = (string) \preg_replace('/^get([A-Z]{1}[a-z]+)$/', '\1', $method, 1);
125
        $routeMethod = \strtolower($routeMethod);
126
127
        if (!\property_exists(__CLASS__, $routeMethod)) {
128
            if (\in_array($routeMethod, ['all', 'arguments'], true)) {
129
                return $this->get($routeMethod);
130
            }
131
132
            throw new \BadMethodCallException(
133
                \sprintf(
134
                    'Method "%s->%s" does not exist. should be one of [%s], all, or arguments. ' .
135
                    '\'%2$s\' method starting with a \'get\' prefix.',
136
                    Route::class,
137
                    $routeMethod ?: $method,
138
                    \join(', ', \array_keys($this->get('all')))
139
                )
140
            );
141
        }
142
143
        return $this->get($routeMethod);
144
    }
145
146
    /**
147
     * Sets the route path prefix.
148
     *
149
     * @param string $path
150
     *
151
     * @return Route $this The current Route instance
152
     */
153
    public function prefix(string $path): self
154
    {
155
        $this->path = $this->castPrefix($this->path, $path);
156
157
        return $this;
158
    }
159
160
    /**
161
     * Sets the route path pattern.
162
     *
163
     * @param string $pattern
164
     *
165
     * @return Route $this The current Route instance
166
     */
167
    public function path(string $pattern): self
168
    {
169
        $this->path = $this->castRoute($pattern);
170
171
        return $this;
172
    }
173
174
    /**
175
     * Sets the route name.
176
     *
177
     * @param string $routeName
178
     *
179
     * @return Route $this The current Route instance
180
     */
181
    public function bind(string $routeName): self
182
    {
183
        $this->name = $routeName;
184
185
        return $this;
186
    }
187
188
    /**
189
     * Sets the route code that should be executed when matched.
190
     *
191
     * @param mixed $to PHP class, object or callable that returns the response when matched
192
     *
193
     * @return Route $this The current Route instance
194
     */
195
    public function run($to): self
196
    {
197
        $this->controller = $to;
198
199
        return $this;
200
    }
201
202
    /**
203
     * Sets the requirement for a route variable.
204
     *
205
     * @param string          $variable The variable name
206
     * @param string|string[] $regexp   The regexp to apply
207
     *
208
     * @return Route $this The current route instance
209
     */
210
    public function assert(string $variable, $regexp): self
211
    {
212
        $this->patterns[$variable] = $regexp;
213
214
        return $this;
215
    }
216
217
    /**
218
     * Sets the requirements for a route variable.
219
     *
220
     * @param array<string,string|string[]> $regexps The regexps to apply
221
     *
222
     * @return Route $this The current route instance
223
     */
224
    public function asserts(array $regexps): self
225
    {
226
        foreach ($regexps as $variable => $regexp) {
227
            $this->assert($variable, $regexp);
228
        }
229
230
        return $this;
231
    }
232
233
    /**
234
     * Sets the default value for a route variable.
235
     *
236
     * @param string $variable The variable name
237
     * @param mixed  $default  The default value
238
     *
239
     * @return Route $this The current Route instance
240
     */
241
    public function default(string $variable, $default): self
242
    {
243
        $this->defaults[$variable] = $default;
244
245
        return $this;
246
    }
247
248
    /**
249
     * Sets the default values for a route variables.
250
     *
251
     * @param array<string,mixed> $values
252
     *
253
     * @return Route $this The current Route instance
254
     */
255
    public function defaults(array $values): self
256
    {
257
        foreach ($values as $variable => $default) {
258
            $this->default($variable, $default);
259
        }
260
261
        return $this;
262
    }
263
264
    /**
265
     * Sets the parameter value for a route handler.
266
     *
267
     * @param int|string $variable The parameter name
268
     * @param mixed      $value    The parameter value
269
     *
270
     * @return Route $this The current Route instance
271
     */
272
    public function argument($variable, $value): self
273
    {
274
        if (!\is_int($variable)) {
275
            if (\is_numeric($value)) {
276
                $value = (int) $value;
277
            } elseif (\is_string($value)) {
278
                $value = \rawurldecode($value);
279
            }
280
281
            $this->defaults['_arguments'][$variable] = $value;
282
        }
283
284
        return $this;
285
    }
286
287
    /**
288
     * Sets the parameter values for a route handler.
289
     *
290
     * @param array<int|string> $variables The route handler parameters
291
     *
292
     * @return Route $this The current Route instance
293
     */
294
    public function arguments(array $variables): self
295
    {
296
        foreach ($variables as $variable => $value) {
297
            $this->argument($variable, $value);
298
        }
299
300
        return $this;
301
    }
302
303
    /**
304
     * Sets the requirement for the HTTP method.
305
     *
306
     * @param string $methods the HTTP method(s) name
307
     *
308
     * @return Route $this The current Route instance
309
     */
310
    public function method(string ...$methods): self
311
    {
312
        foreach ($methods as $method) {
313
            $this->methods[\strtoupper($method)] = true;
314
        }
315
316
        return $this;
317
    }
318
319
    /**
320
     * Sets the requirement of host on this Route.
321
     *
322
     * @param string $hosts The host for which this route should be enabled
323
     *
324
     * @return Route $this The current Route instance
325
     */
326
    public function domain(string ...$hosts): self
327
    {
328
        foreach ($hosts as $host) {
329
            \preg_match(Route::URL_PATTERN, $host, $matches);
330
331
            $scheme = $matches['scheme'] ?? '';
332
333
            if ('api' === $scheme && isset($matches['host'])) {
334
                $this->defaults['_api'] = \ucfirst($matches['host']);
335
336
                continue;
337
            }
338
339
            if (!empty($scheme)) {
340
                $this->schemes[$scheme] = true;
341
            }
342
343
            if (!empty($matches['host'])) {
344
                $this->domain[$matches['host']] = true;
345
            }
346
        }
347
348
        return $this;
349
    }
350
351
    /**
352
     * Sets the requirement of domain scheme on this Route.
353
     *
354
     * @param string ...$schemes
355
     *
356
     * @return Route $this The current Route instance
357
     */
358
    public function scheme(string ...$schemes): self
359
    {
360
        foreach ($schemes as $scheme) {
361
            $this->schemes[$scheme] = true;
362
        }
363
364
        return $this;
365
    }
366
367
    /**
368
     * Sets the middleware(s) to handle before triggering the route handler
369
     *
370
     * @param mixed ...$middlewares
371
     *
372
     * @return Route $this The current Route instance
373
     */
374
    public function middleware(...$middlewares): self
375
    {
376
        /** @var int|string $index */
377
        foreach ($middlewares as $index => $middleware) {
378
            if (!\is_callable($middleware) && (\is_int($index) && \is_array($middleware))) {
379
                $this->middleware(...$middleware);
380
381
                continue;
382
            }
383
384
            $this->middlewares[] = $middleware;
385
        }
386
387
        return $this;
388
    }
389
390
    /**
391
     * Get any of (name, path, domain, defaults, schemes, domain, controller, patterns, middlewares).
392
     * And also accepts "all" and "arguments".
393
     *
394
     * @param string $name
395
     *
396
     * @return mixed
397
     */
398
    public function get(string $name)
399
    {
400
        if (\property_exists(__CLASS__, $name)) {
401
            return $this->{$name};
402
        }
403
404
        if ('all' === $name) {
405
            return [
406
                'controller'  => $this->controller,
407
                'methods'     => $this->methods,
408
                'schemes'     => $this->schemes,
409
                'domain'      => $this->domain,
410
                'name'        => $this->name,
411
                'path'        => $this->path,
412
                'patterns'    => $this->patterns,
413
                'middlewares' => $this->middlewares,
414
                'defaults'    => $this->defaults,
415
            ];
416
        }
417
418
        if ('arguments' === $name) {
419
            return $this->defaults['_arguments'] ?? [];
420
        }
421
422
        return null;
423
    }
424
425
    public function generateRouteName(string $prefix): string
426
    {
427
        $methods = \implode('_', \array_keys($this->methods)) . '_';
428
429
        $routeName = $methods . $prefix . $this->path;
430
        $routeName = \str_replace(['/', ':', '|', '-'], '_', $routeName);
431
        $routeName = (string) \preg_replace('/[^a-z0-9A-Z_.]+/', '', $routeName);
432
433
        // Collapse consecutive underscores down into a single underscore.
434
        $routeName = (string) \preg_replace('/_+/', '_', $routeName);
435
436
        return $routeName;
437
    }
438
}
439