Completed
Push — 2.1 ( 7c8525...0afc41 )
by Alexander
21:05 queued 16:02
created

UrlRule::getCreateUrlStatus()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\web;
9
10
use Yii;
11
use yii\base\InvalidConfigException;
12
use yii\base\Object;
13
14
/**
15
 * UrlRule represents a rule used by [[UrlManager]] for parsing and generating URLs.
16
 *
17
 * To define your own URL parsing and creation logic you can extend from this class
18
 * and add it to [[UrlManager::rules]] like this:
19
 *
20
 * ```php
21
 * 'rules' => [
22
 *     ['class' => MyUrlRule::class, 'pattern' => '...', 'route' => 'site/index', ...],
23
 *     // ...
24
 * ]
25
 * ```
26
 *
27
 * @property null|int $createUrlStatus Status of the URL creation after the last [[createUrl()]] call. `null`
28
 * if rule does not provide info about create status. This property is read-only.
29
 *
30
 * @author Qiang Xue <[email protected]>
31
 * @since 2.0
32
 */
33
class UrlRule extends Object implements UrlRuleInterface
34
{
35
    /**
36
     * Set [[mode]] with this value to mark that this rule is for URL parsing only
37
     */
38
    const PARSING_ONLY = 1;
39
    /**
40
     * Set [[mode]] with this value to mark that this rule is for URL creation only
41
     */
42
    const CREATION_ONLY = 2;
43
    /**
44
     * Represents the successful URL generation by last [[createUrl()]] call.
45
     * @see $createStatus
46
     * @since 2.0.12
47
     */
48
    const CREATE_STATUS_SUCCESS = 0;
49
    /**
50
     * Represents the unsuccessful URL generation by last [[createUrl()]] call, because rule does not support
51
     * creating URLs.
52
     * @see $createStatus
53
     * @since 2.0.12
54
     */
55
    const CREATE_STATUS_PARSING_ONLY = 1;
56
    /**
57
     * Represents the unsuccessful URL generation by last [[createUrl()]] call, because of mismatched route.
58
     * @see $createStatus
59
     * @since 2.0.12
60
     */
61
    const CREATE_STATUS_ROUTE_MISMATCH = 2;
62
    /**
63
     * Represents the unsuccessful URL generation by last [[createUrl()]] call, because of mismatched
64
     * or missing parameters.
65
     * @see $createStatus
66
     * @since 2.0.12
67
     */
68
    const CREATE_STATUS_PARAMS_MISMATCH = 4;
69
70
    /**
71
     * @var string the name of this rule. If not set, it will use [[pattern]] as the name.
72
     */
73
    public $name;
74
    /**
75
     * On the rule initialization, the [[pattern]] matching parameters names will be replaced with [[placeholders]].
76
     * @var string the pattern used to parse and create the path info part of a URL.
77
     * @see host
78
     * @see placeholders
79
     */
80
    public $pattern;
81
    /**
82
     * @var string the pattern used to parse and create the host info part of a URL (e.g. `http://example.com`).
83
     * @see pattern
84
     */
85
    public $host;
86
    /**
87
     * @var string the route to the controller action
88
     */
89
    public $route;
90
    /**
91
     * @var array the default GET parameters (name => value) that this rule provides.
92
     * When this rule is used to parse the incoming request, the values declared in this property
93
     * will be injected into $_GET.
94
     */
95
    public $defaults = [];
96
    /**
97
     * @var string the URL suffix used for this rule.
98
     * For example, ".html" can be used so that the URL looks like pointing to a static HTML page.
99
     * If not set, the value of [[UrlManager::suffix]] will be used.
100
     */
101
    public $suffix;
102
    /**
103
     * @var string|array the HTTP verb (e.g. GET, POST, DELETE) that this rule should match.
104
     * Use array to represent multiple verbs that this rule may match.
105
     * If this property is not set, the rule can match any verb.
106
     * Note that this property is only used when parsing a request. It is ignored for URL creation.
107
     */
108
    public $verb;
109
    /**
110
     * @var int a value indicating if this rule should be used for both request parsing and URL creation,
111
     * parsing only, or creation only.
112
     * If not set or 0, it means the rule is both request parsing and URL creation.
113
     * If it is [[PARSING_ONLY]], the rule is for request parsing only.
114
     * If it is [[CREATION_ONLY]], the rule is for URL creation only.
115
     */
116
    public $mode;
117
    /**
118
     * @var bool a value indicating if parameters should be url encoded.
119
     */
120
    public $encodeParams = true;
121
    /**
122
     * @var UrlNormalizer|array|false|null the configuration for [[UrlNormalizer]] used by this rule.
123
     * If `null`, [[UrlManager::normalizer]] will be used, if `false`, normalization will be skipped
124
     * for this rule.
125
     * @since 2.0.10
126
     */
127
    public $normalizer;
128
129
    /**
130
     * @var int|null status of the URL creation after the last [[createUrl()]] call.
131
     * @since 2.0.12
132
     */
133
    protected $createStatus;
134
    /**
135
     * @var array list of placeholders for matching parameters names. Used in [[parseRequest()]], [[createUrl()]].
136
     * On the rule initialization, the [[pattern]] parameters names will be replaced with placeholders.
137
     * This array contains relations between the original parameters names and their placeholders.
138
     * The array keys are the placeholders and the values are the original names.
139
     *
140
     * @see parseRequest()
141
     * @see createUrl()
142
     * @since 2.0.7
143
     */
144
    protected $placeholders = [];
145
146
    /**
147
     * @var string the template for generating a new URL. This is derived from [[pattern]] and is used in generating URL.
148
     */
149
    private $_template;
150
    /**
151
     * @var string the regex for matching the route part. This is used in generating URL.
152
     */
153
    private $_routeRule;
154
    /**
155
     * @var array list of regex for matching parameters. This is used in generating URL.
156
     */
157
    private $_paramRules = [];
158
    /**
159
     * @var array list of parameters used in the route.
160
     */
161
    private $_routeParams = [];
162
163
164
    /**
165
     * @return string
166
     * @since 2.0.11
167
     */
168 12
    public function __toString()
169
    {
170 12
        $str = '';
171 12
        if ($this->verb !== null) {
172 3
            $str .= implode(',', $this->verb) . ' ';
173
        }
174 12
        if ($this->host !== null && strrpos($this->name, $this->host) === false) {
175 1
            $str .= $this->host . '/';
176
        }
177 12
        $str .= $this->name;
178
179 12
        if ($str === '') {
180 1
            return '/';
181
        }
182 12
        return $str;
183
    }
184
185
    /**
186
     * Initializes this rule.
187
     */
188 94
    public function init()
189
    {
190 94
        if ($this->pattern === null) {
191
            throw new InvalidConfigException('UrlRule::pattern must be set.');
192
        }
193 94
        if ($this->route === null) {
194
            throw new InvalidConfigException('UrlRule::route must be set.');
195
        }
196 94
        if (is_array($this->normalizer)) {
197 1
            $normalizerConfig = array_merge(['class' => UrlNormalizer::class], $this->normalizer);
198 1
            $this->normalizer = Yii::createObject($normalizerConfig);
199
        }
200 94
        if ($this->normalizer !== null && $this->normalizer !== false && !$this->normalizer instanceof UrlNormalizer) {
201
            throw new InvalidConfigException('Invalid config for UrlRule::normalizer.');
202
        }
203 94
        if ($this->verb !== null) {
204 13
            if (is_array($this->verb)) {
205 13
                foreach ($this->verb as $i => $verb) {
206 13
                    $this->verb[$i] = strtoupper($verb);
207
                }
208
            } else {
209
                $this->verb = [strtoupper($this->verb)];
210
            }
211
        }
212 94
        if ($this->name === null) {
213 94
            $this->name = $this->pattern;
214
        }
215
216 94
        $this->preparePattern();
217 94
    }
218
219
    /**
220
     * Process [[$pattern]] on rule initialization.
221
     */
222 94
    private function preparePattern()
223
    {
224 94
        $this->pattern = $this->trimSlashes($this->pattern);
225 94
        $this->route = trim($this->route, '/');
226
227 94
        if ($this->host !== null) {
228 17
            $this->host = rtrim($this->host, '/');
229 17
            $this->pattern = rtrim($this->host . '/' . $this->pattern, '/');
230 90
        } elseif ($this->pattern === '') {
231 21
            $this->_template = '';
232 21
            $this->pattern = '#^$#u';
233
234 21
            return;
235 82
        } elseif (($pos = strpos($this->pattern, '://')) !== false) {
236 9
            if (($pos2 = strpos($this->pattern, '/', $pos + 3)) !== false) {
237 9
                $this->host = substr($this->pattern, 0, $pos2);
238
            } else {
239
                $this->host = $this->pattern;
240
            }
241 78
        } elseif (strpos($this->pattern, '//') === 0) {
242 8
            if (($pos2 = strpos($this->pattern, '/', 2)) !== false) {
243 8
                $this->host = substr($this->pattern, 0, $pos2);
244
            } else {
245 4
                $this->host = $this->pattern;
246
            }
247
        } else {
248 74
            $this->pattern = '/' . $this->pattern . '/';
249
        }
250
251 86
        if (strpos($this->route, '<') !== false && preg_match_all('/<([\w._-]+)>/', $this->route, $matches)) {
252 15
            foreach ($matches[1] as $name) {
253 15
                $this->_routeParams[$name] = "<$name>";
254
            }
255
        }
256
257 86
        $this->translatePattern(true);
258 86
    }
259
260
    /**
261
     * Prepares [[$pattern]] on rule initialization - replace parameter names by placeholders.
262
     *
263
     * @param bool $allowAppendSlash Defines position of slash in the param pattern in [[$pattern]].
264
     * If `false` slash will be placed at the beginning of param pattern. If `true` slash position will be detected
265
     * depending on non-optional pattern part.
266
     */
267 86
    private function translatePattern($allowAppendSlash)
268
    {
269
        $tr = [
270 86
            '.' => '\\.',
271
            '*' => '\\*',
272
            '$' => '\\$',
273
            '[' => '\\[',
274
            ']' => '\\]',
275
            '(' => '\\(',
276
            ')' => '\\)',
277
        ];
278
279 86
        $tr2 = [];
280 86
        $requiredPatternPart = $this->pattern;
281 86
        $oldOffset = 0;
282 86
        if (preg_match_all('/<([\w._-]+):?([^>]+)?>/', $this->pattern, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
283 85
            $appendSlash = false;
284 85
            foreach ($matches as $match) {
285 85
                $name = $match[1][0];
286 85
                $pattern = isset($match[2][0]) ? $match[2][0] : '[^\/]+';
287 85
                $placeholder = 'a' . hash('crc32b', $name); // placeholder must begin with a letter
288 85
                $this->placeholders[$placeholder] = $name;
289 85
                if (array_key_exists($name, $this->defaults)) {
290 16
                    $length = strlen($match[0][0]);
291 16
                    $offset = $match[0][1];
292 16
                    $requiredPatternPart = str_replace("/{$match[0][0]}/", '//', $requiredPatternPart);
293
                    if (
294 16
                        $allowAppendSlash
295 16
                        && ($appendSlash || $offset === 1)
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison === seems to always evaluate to false as the types of $offset (string) and 1 (integer) can never be identical. Maybe you want to use a loose comparison == instead?
Loading history...
296 12
                        && (($offset - $oldOffset) === 1)
297 12
                        && isset($this->pattern[$offset + $length])
298 12
                        && $this->pattern[$offset + $length] === '/'
299 12
                        && isset($this->pattern[$offset + $length + 1])
300
                    ) {
301
                        // if pattern starts from optional params, put slash at the end of param pattern
302
                        // @see https://github.com/yiisoft/yii2/issues/13086
303 4
                        $appendSlash = true;
304 4
                        $tr["<$name>/"] = "((?P<$placeholder>$pattern)/)?";
305
                    } elseif (
306 16
                        $offset > 1
307 8
                        && $this->pattern[$offset - 1] === '/'
308 8
                        && (!isset($this->pattern[$offset + $length]) || $this->pattern[$offset + $length] === '/')
309
                    ) {
310 8
                        $appendSlash = false;
311 8
                        $tr["/<$name>"] = "(/(?P<$placeholder>$pattern))?";
312
                    }
313 16
                    $tr["<$name>"] = "(?P<$placeholder>$pattern)?";
314 16
                    $oldOffset = $offset + $length;
315
                } else {
316 85
                    $appendSlash = false;
317 85
                    $tr["<$name>"] = "(?P<$placeholder>$pattern)";
318
                }
319
320 85
                if (isset($this->_routeParams[$name])) {
321 15
                    $tr2["<$name>"] = "(?P<$placeholder>$pattern)";
322
                } else {
323 85
                    $this->_paramRules[$name] = $pattern === '[^\/]+' ? '' : "#^$pattern$#u";
324
                }
325
            }
326
        }
327
328
        // we have only optional params in route - ensure slash position on param patterns
329 86
        if ($allowAppendSlash && trim($requiredPatternPart, '/') === '') {
330 12
            $this->translatePattern(false);
331 12
            return;
332
        }
333
334 86
        $this->_template = preg_replace('/<([\w._-]+):?([^>]+)?>/', '<$1>', $this->pattern);
335 86
        $this->pattern = '#^' . trim(strtr($this->_template, $tr), '/') . '$#u';
336
337
        // if host starts with relative scheme, then insert pattern to match any
338 86
        if (strpos($this->host, '//') === 0) {
339 8
            $this->pattern = substr_replace($this->pattern, '[\w]+://', 2, 0);
340
        }
341
342 86
        if (!empty($this->_routeParams)) {
343 15
            $this->_routeRule = '#^' . strtr($this->route, $tr2) . '$#u';
344
        }
345 86
    }
346
347
    /**
348
     * @param UrlManager $manager the URL manager
349
     * @return UrlNormalizer|null
350
     * @since 2.0.10
351
     */
352 15
    protected function getNormalizer($manager)
353
    {
354 15
        if ($this->normalizer === null) {
355 14
            return $manager->normalizer;
356
        } else {
357 1
            return $this->normalizer;
358
        }
359
    }
360
361
    /**
362
     * @param UrlManager $manager the URL manager
363
     * @return bool
364
     * @since 2.0.10
365
     */
366 15
    protected function hasNormalizer($manager)
367
    {
368 15
        return $this->getNormalizer($manager) instanceof UrlNormalizer;
369
    }
370
371
    /**
372
     * Parses the given request and returns the corresponding route and parameters.
373
     * @param UrlManager $manager the URL manager
374
     * @param Request $request the request component
375
     * @return array|bool the parsing result. The route and the parameters are returned as an array.
376
     * If `false`, it means this rule cannot be used to parse this path info.
377
     */
378 15
    public function parseRequest($manager, $request)
379
    {
380 15
        if ($this->mode === self::CREATION_ONLY) {
381 3
            return false;
382
        }
383
384 15
        if (!empty($this->verb) && !in_array($request->getMethod(), $this->verb, true)) {
385 2
            return false;
386
        }
387
388 15
        $suffix = (string)($this->suffix === null ? $manager->suffix : $this->suffix);
389 15
        $pathInfo = $request->getPathInfo();
390 15
        $normalized = false;
391 15
        if ($this->hasNormalizer($manager)) {
392 8
            $pathInfo = $this->getNormalizer($manager)->normalizePathInfo($pathInfo, $suffix, $normalized);
393
        }
394 15
        if ($suffix !== '' && $pathInfo !== '') {
395 9
            $n = strlen($suffix);
396 9
            if (substr_compare($pathInfo, $suffix, -$n, $n) === 0) {
397 9
                $pathInfo = substr($pathInfo, 0, -$n);
398 9
                if ($pathInfo === '') {
399
                    // suffix alone is not allowed
400 3
                    return false;
401
                }
402
            } else {
403 8
                return false;
404
            }
405
        }
406
407 15
        if ($this->host !== null) {
408 3
            $pathInfo = strtolower($request->getHostInfo()) . ($pathInfo === '' ? '' : '/' . $pathInfo);
409
        }
410
411 15
        if (!preg_match($this->pattern, $pathInfo, $matches)) {
412 14
            return false;
413
        }
414 15
        $matches = $this->substitutePlaceholderNames($matches);
415
416 15
        foreach ($this->defaults as $name => $value) {
417 3
            if (!isset($matches[$name]) || $matches[$name] === '') {
418 3
                $matches[$name] = $value;
419
            }
420
        }
421 15
        $params = $this->defaults;
422 15
        $tr = [];
423 15
        foreach ($matches as $name => $value) {
424 15
            if (isset($this->_routeParams[$name])) {
425 3
                $tr[$this->_routeParams[$name]] = $value;
426 3
                unset($params[$name]);
427 15
            } elseif (isset($this->_paramRules[$name])) {
428 14
                $params[$name] = $value;
429
            }
430
        }
431 15
        if ($this->_routeRule !== null) {
432 3
            $route = strtr($this->route, $tr);
433
        } else {
434 15
            $route = $this->route;
435
        }
436
437 15
        Yii::trace("Request parsed with URL rule: {$this->name}", __METHOD__);
438
439 15
        if ($normalized) {
440
            // pathInfo was changed by normalizer - we need also normalize route
441 4
            return $this->getNormalizer($manager)->normalizeRoute([$route, $params]);
442
        } else {
443 13
            return [$route, $params];
444
        }
445
    }
446
447
    /**
448
     * Creates a URL according to the given route and parameters.
449
     * @param UrlManager $manager the URL manager
450
     * @param string $route the route. It should not have slashes at the beginning or the end.
451
     * @param array $params the parameters
452
     * @return string|bool the created URL, or `false` if this rule cannot be used for creating this URL.
453
     */
454 78
    public function createUrl($manager, $route, $params)
455
    {
456 78
        if ($this->mode === self::PARSING_ONLY) {
457 13
            $this->createStatus = self::CREATE_STATUS_PARSING_ONLY;
458 13
            return false;
459
        }
460
461 77
        $tr = [];
462
463
        // match the route part first
464 77
        if ($route !== $this->route) {
465 64
            if ($this->_routeRule !== null && preg_match($this->_routeRule, $route, $matches)) {
466 12
                $matches = $this->substitutePlaceholderNames($matches);
467 12
                foreach ($this->_routeParams as $name => $token) {
468 12
                    if (isset($this->defaults[$name]) && strcmp($this->defaults[$name], $matches[$name]) === 0) {
469 1
                        $tr[$token] = '';
470
                    } else {
471 12
                        $tr[$token] = $matches[$name];
472
                    }
473
                }
474
            } else {
475 63
                $this->createStatus = self::CREATE_STATUS_ROUTE_MISMATCH;
476 63
                return false;
477
            }
478
        }
479
480
        // match default params
481
        // if a default param is not in the route pattern, its value must also be matched
482 76
        foreach ($this->defaults as $name => $value) {
483 15
            if (isset($this->_routeParams[$name])) {
484 1
                continue;
485
            }
486 15
            if (!isset($params[$name])) {
487
                // allow omit empty optional params
488
                // @see https://github.com/yiisoft/yii2/issues/10970
489 10
                if (in_array($name, $this->placeholders) && strcmp($value, '') === 0) {
490 1
                    $params[$name] = '';
491
                } else {
492 10
                    $this->createStatus = self::CREATE_STATUS_PARAMS_MISMATCH;
493 10
                    return false;
494
                }
495
            }
496 15
            if (strcmp($params[$name], $value) === 0) { // strcmp will do string conversion automatically
497 15
                unset($params[$name]);
498 15
                if (isset($this->_paramRules[$name])) {
499 11
                    $tr["<$name>"] = '';
500
                }
501 14
            } elseif (!isset($this->_paramRules[$name])) {
502 13
                $this->createStatus = self::CREATE_STATUS_PARAMS_MISMATCH;
503 13
                return false;
504
            }
505
        }
506
507
        // match params in the pattern
508 76
        foreach ($this->_paramRules as $name => $rule) {
509 68
            if (isset($params[$name]) && !is_array($params[$name]) && ($rule === '' || preg_match($rule, $params[$name]))) {
510 66
                $tr["<$name>"] = $this->encodeParams ? urlencode($params[$name]) : $params[$name];
511 66
                unset($params[$name]);
512 56
            } elseif (!isset($this->defaults[$name]) || isset($params[$name])) {
513 55
                $this->createStatus = self::CREATE_STATUS_PARAMS_MISMATCH;
514 55
                return false;
515
            }
516
        }
517
518 76
        $url = $this->trimSlashes(strtr($this->_template, $tr));
519 76
        if ($this->host !== null) {
520 13
            $pos = strpos($url, '/', 8);
521 13
            if ($pos !== false) {
522 13
                $url = substr($url, 0, $pos) . preg_replace('#/+#', '/', substr($url, $pos));
523
            }
524 64
        } elseif (strpos($url, '//') !== false) {
525 11
            $url = preg_replace('#/+#', '/', trim($url, '/'));
526
        }
527
528 76
        if ($url !== '') {
529 68
            $url .= ($this->suffix === null ? $manager->suffix : $this->suffix);
530
        }
531
532 76
        if (!empty($params) && ($query = http_build_query($params)) !== '') {
533 55
            $url .= '?' . $query;
534
        }
535
536 76
        $this->createStatus = self::CREATE_STATUS_SUCCESS;
537 76
        return $url;
538
    }
539
540
    /**
541
     * Returns status of the URL creation after the last [[createUrl()]] call.
542
     *
543
     * @return null|int Status of the URL creation after the last [[createUrl()]] call. `null` if rule does not provide
544
     * info about create status.
545
     * @see $createStatus
546
     * @since 2.0.12
547
     */
548 77
    public function getCreateUrlStatus() {
549 77
        return $this->createStatus;
550
    }
551
552
    /**
553
     * Returns list of regex for matching parameter.
554
     * @return array parameter keys and regexp rules.
555
     *
556
     * @since 2.0.6
557
     */
558
    protected function getParamRules()
559
    {
560
        return $this->_paramRules;
561
    }
562
563
    /**
564
     * Iterates over [[placeholders]] and checks whether each placeholder exists as a key in $matches array.
565
     * When found - replaces this placeholder key with a appropriate name of matching parameter.
566
     * Used in [[parseRequest()]], [[createUrl()]].
567
     *
568
     * @param array $matches result of `preg_match()` call
569
     * @return array input array with replaced placeholder keys
570
     * @see placeholders
571
     * @since 2.0.7
572
     */
573 27
    protected function substitutePlaceholderNames(array $matches)
574
    {
575 27
        foreach ($this->placeholders as $placeholder => $name) {
576 26
            if (isset($matches[$placeholder])) {
577 26
                $matches[$name] = $matches[$placeholder];
578 26
                unset($matches[$placeholder]);
579
            }
580
        }
581 27
        return $matches;
582
    }
583
584
    /**
585
     * Trim slashes in passed string. If string begins with '//', two slashes are left as is
586
     * in the beginning of a string.
587
     *
588
     * @param string $string
589
     * @return string
590
     */
591 94
    private function trimSlashes($string)
592
    {
593 94
        if (strpos($string, '//') === 0) {
594 16
            return '//' . trim($string, '/');
595
        }
596 94
        return trim($string, '/');
597
    }
598
}
599