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