UrlRule::parseRequest()   F
last analyzed

Complexity

Conditions 21
Paths 1186

Size

Total Lines 67
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 40
CRAP Score 21

Importance

Changes 0
Metric Value
cc 21
eloc 41
nc 1186
nop 2
dl 0
loc 67
ccs 40
cts 40
cp 1
crap 21
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * @link https://www.yiiframework.com/
5
 * @copyright Copyright (c) 2008 Yii Software LLC
6
 * @license https://www.yiiframework.com/license/
7
 */
8
9
namespace yii\web;
10
11
use Yii;
12
use yii\base\BaseObject;
13
use yii\base\InvalidConfigException;
14
15
/**
16
 * UrlRule represents a rule used by [[UrlManager]] for parsing and generating URLs.
17
 *
18
 * To define your own URL parsing and creation logic you can extend from this class
19
 * and add it to [[UrlManager::rules]] like this:
20
 *
21
 * ```php
22
 * 'rules' => [
23
 *     ['class' => 'MyUrlRule', 'pattern' => '...', 'route' => 'site/index', ...],
24
 *     // ...
25
 * ]
26
 * ```
27
 *
28
 * @property-read int|null $createUrlStatus Status of the URL creation after the last [[createUrl()]] call.
29
 * `null` if rule does not provide info about create status.
30
 *
31
 * @author Qiang Xue <[email protected]>
32
 * @since 2.0
33
 */
34
class UrlRule extends BaseObject implements UrlRuleInterface
35
{
36
    /**
37
     * Set [[mode]] with this value to mark that this rule is for URL parsing only.
38
     */
39
    const PARSING_ONLY = 1;
40
    /**
41
     * Set [[mode]] with this value to mark that this rule is for URL creation only.
42
     */
43
    const CREATION_ONLY = 2;
44
    /**
45
     * Represents the successful URL generation by last [[createUrl()]] call.
46
     * @see createStatus
47
     * @since 2.0.12
48
     */
49
    const CREATE_STATUS_SUCCESS = 0;
50
    /**
51
     * Represents the unsuccessful URL generation by last [[createUrl()]] call, because rule does not support
52
     * creating URLs.
53
     * @see createStatus
54
     * @since 2.0.12
55
     */
56
    const CREATE_STATUS_PARSING_ONLY = 1;
57
    /**
58
     * Represents the unsuccessful URL generation by last [[createUrl()]] call, because of mismatched route.
59
     * @see createStatus
60
     * @since 2.0.12
61
     */
62
    const CREATE_STATUS_ROUTE_MISMATCH = 2;
63
    /**
64
     * Represents the unsuccessful URL generation by last [[createUrl()]] call, because of mismatched
65
     * or missing parameters.
66
     * @see createStatus
67
     * @since 2.0.12
68
     */
69
    const CREATE_STATUS_PARAMS_MISMATCH = 4;
70
71
    /**
72
     * @var string|null the name of this rule. If not set, it will use [[pattern]] as the name.
73
     */
74
    public $name;
75
    /**
76
     * On the rule initialization, the [[pattern]] matching parameters names will be replaced with [[placeholders]].
77
     * @var string the pattern used to parse and create the path info part of a URL.
78
     * @see host
79
     * @see placeholders
80
     */
81
    public $pattern;
82
    /**
83
     * @var string|null the pattern used to parse and create the host info part of a URL (e.g. `https://example.com`).
84
     * @see pattern
85
     */
86
    public $host;
87
    /**
88
     * @var string the route to the controller action
89
     */
90
    public $route;
91
    /**
92
     * @var array the default GET parameters (name => value) that this rule provides.
93
     * When this rule is used to parse the incoming request, the values declared in this property
94
     * will be injected into $_GET.
95
     */
96
    public $defaults = [];
97
    /**
98
     * @var string|null the URL suffix used for this rule.
99
     * For example, ".html" can be used so that the URL looks like pointing to a static HTML page.
100
     * If not set, the value of [[UrlManager::suffix]] will be used.
101
     */
102
    public $suffix;
103
    /**
104
     * @var string|array|null the HTTP verb (e.g. GET, POST, DELETE) that this rule should match.
105
     * Use array to represent multiple verbs that this rule may match.
106
     * If this property is not set, the rule can match any verb.
107
     * Note that this property is only used when parsing a request. It is ignored for URL creation.
108
     */
109
    public $verb;
110
    /**
111
     * @var int|null a value indicating if this rule should be used for both request parsing and URL creation,
112
     * parsing only, or creation only.
113
     * If not set or 0, it means the rule is both request parsing and URL creation.
114
     * If it is [[PARSING_ONLY]], the rule is for request parsing only.
115
     * If it is [[CREATION_ONLY]], the rule is for URL creation only.
116
     */
117
    public $mode;
118
    /**
119
     * @var bool a value indicating if parameters should be url encoded.
120
     */
121
    public $encodeParams = true;
122
    /**
123
     * @var UrlNormalizer|array|false|null the configuration for [[UrlNormalizer]] used by this rule.
124
     * If `null`, [[UrlManager::normalizer]] will be used, if `false`, normalization will be skipped
125
     * for this rule.
126
     * @since 2.0.10
127
     */
128
    public $normalizer;
129
130
    /**
131
     * @var int|null status of the URL creation after the last [[createUrl()]] call.
132
     * @since 2.0.12
133
     */
134
    protected $createStatus;
135
    /**
136
     * @var array list of placeholders for matching parameters names. Used in [[parseRequest()]], [[createUrl()]].
137
     * On the rule initialization, the [[pattern]] parameters names will be replaced with placeholders.
138
     * This array contains relations between the original parameters names and their placeholders.
139
     * The array keys are the placeholders and the values are the original names.
140
     *
141
     * @see parseRequest()
142
     * @see createUrl()
143
     * @since 2.0.7
144
     */
145
    protected $placeholders = [];
146
147
    /**
148
     * @var string the template for generating a new URL. This is derived from [[pattern]] and is used in generating URL.
149
     */
150
    private $_template;
151
    /**
152
     * @var string the regex for matching the route part. This is used in generating URL.
153
     */
154
    private $_routeRule;
155
    /**
156
     * @var array list of regex for matching parameters. This is used in generating URL.
157
     */
158
    private $_paramRules = [];
159
    /**
160
     * @var array list of parameters used in the route.
161
     */
162
    private $_routeParams = [];
163
164
165
    /**
166
     * @return string
167
     * @since 2.0.11
168
     */
169 13
    public function __toString()
170
    {
171 13
        $str = '';
172 13
        if ($this->verb !== null) {
173 3
            $str .= implode(',', $this->verb) . ' ';
0 ignored issues
show
Bug introduced by
It seems like $this->verb can also be of type string; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

173
            $str .= implode(',', /** @scrutinizer ignore-type */ $this->verb) . ' ';
Loading history...
174
        }
175 13
        if ($this->host !== null && strrpos($this->name, $this->host) === false) {
0 ignored issues
show
Bug introduced by
It seems like $this->name can also be of type null; however, parameter $haystack of strrpos() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

175
        if ($this->host !== null && strrpos(/** @scrutinizer ignore-type */ $this->name, $this->host) === false) {
Loading history...
176 1
            $str .= $this->host . '/';
177
        }
178 13
        $str .= $this->name;
179
180 13
        if ($str === '') {
181 1
            return '/';
182
        }
183
184 13
        return $str;
185
    }
186
187
    /**
188
     * Initializes this rule.
189
     */
190 101
    public function init()
191
    {
192 101
        if ($this->pattern === null) {
193
            throw new InvalidConfigException('UrlRule::pattern must be set.');
194
        }
195 101
        if ($this->route === null) {
196
            throw new InvalidConfigException('UrlRule::route must be set.');
197
        }
198 101
        if (is_array($this->normalizer)) {
199 1
            $normalizerConfig = array_merge(['class' => UrlNormalizer::className()], $this->normalizer);
0 ignored issues
show
Deprecated Code introduced by
The function yii\base\BaseObject::className() has been deprecated: since 2.0.14. On PHP >=5.5, use `::class` instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

199
            $normalizerConfig = array_merge(['class' => /** @scrutinizer ignore-deprecated */ UrlNormalizer::className()], $this->normalizer);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
200 1
            $this->normalizer = Yii::createObject($normalizerConfig);
201
        }
202 101
        if ($this->normalizer !== null && $this->normalizer !== false && !$this->normalizer instanceof UrlNormalizer) {
203
            throw new InvalidConfigException('Invalid config for UrlRule::normalizer.');
204
        }
205 101
        if ($this->verb !== null) {
206 22
            if (is_array($this->verb)) {
207 22
                foreach ($this->verb as $i => $verb) {
208 22
                    $this->verb[$i] = strtoupper($verb);
209
                }
210
            } else {
211 1
                $this->verb = [strtoupper($this->verb)];
212
            }
213
        }
214 101
        if ($this->name === null) {
215 101
            $this->name = $this->pattern;
216
        }
217
218 101
        $this->preparePattern();
219
    }
220
221
    /**
222
     * Process [[$pattern]] on rule initialization.
223
     */
224 101
    private function preparePattern()
225
    {
226 101
        $this->pattern = $this->trimSlashes($this->pattern);
227 101
        $this->route = trim($this->route, '/');
228
229 101
        if ($this->host !== null) {
230 17
            $this->host = rtrim($this->host, '/');
231 17
            $this->pattern = rtrim($this->host . '/' . $this->pattern, '/');
232 97
        } elseif ($this->pattern === '') {
233 23
            $this->_template = '';
234 23
            $this->pattern = '#^$#u';
235
236 23
            return;
237 87
        } elseif (($pos = strpos($this->pattern, '://')) !== false) {
238 9
            if (($pos2 = strpos($this->pattern, '/', $pos + 3)) !== false) {
239 9
                $this->host = substr($this->pattern, 0, $pos2);
240
            } else {
241 9
                $this->host = $this->pattern;
242
            }
243 83
        } elseif (strncmp($this->pattern, '//', 2) === 0) {
244 8
            if (($pos2 = strpos($this->pattern, '/', 2)) !== false) {
245 8
                $this->host = substr($this->pattern, 0, $pos2);
246
            } else {
247 8
                $this->host = $this->pattern;
248
            }
249
        } else {
250 79
            $this->pattern = '/' . $this->pattern . '/';
251
        }
252
253 91
        if (strpos($this->route, '<') !== false && preg_match_all('/<([\w._-]+)>/', $this->route, $matches)) {
254 16
            foreach ($matches[1] as $name) {
255 16
                $this->_routeParams[$name] = "<$name>";
256
            }
257
        }
258
259 91
        $this->translatePattern(true);
260
    }
261
262
    /**
263
     * Prepares [[$pattern]] on rule initialization - replace parameter names by placeholders.
264
     *
265
     * @param bool $allowAppendSlash Defines position of slash in the param pattern in [[$pattern]].
266
     * If `false` slash will be placed at the beginning of param pattern. If `true` slash position will be detected
267
     * depending on non-optional pattern part.
268
     */
269 91
    private function translatePattern($allowAppendSlash)
270
    {
271 91
        $tr = [
272 91
            '.' => '\\.',
273 91
            '*' => '\\*',
274 91
            '$' => '\\$',
275 91
            '[' => '\\[',
276 91
            ']' => '\\]',
277 91
            '(' => '\\(',
278 91
            ')' => '\\)',
279 91
        ];
280
281 91
        $tr2 = [];
282 91
        $requiredPatternPart = $this->pattern;
283 91
        $oldOffset = 0;
284 91
        if (preg_match_all('/<([\w._-]+):?([^>]+)?>/', $this->pattern, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
285 89
            $appendSlash = false;
286 89
            foreach ($matches as $match) {
287 89
                $name = $match[1][0];
288 89
                $pattern = isset($match[2][0]) ? $match[2][0] : '[^\/]+';
289 89
                $placeholder = 'a' . hash('crc32b', $name); // placeholder must begin with a letter
290 89
                $this->placeholders[$placeholder] = $name;
291 89
                if (array_key_exists($name, $this->defaults)) {
292 16
                    $length = strlen($match[0][0]);
293 16
                    $offset = $match[0][1];
294 16
                    $requiredPatternPart = str_replace("/{$match[0][0]}/", '//', $requiredPatternPart);
295
                    if (
296 16
                        $allowAppendSlash
297 16
                        && ($appendSlash || $offset === 1)
298 16
                        && (($offset - $oldOffset) === 1)
299 16
                        && isset($this->pattern[$offset + $length])
300 16
                        && $this->pattern[$offset + $length] === '/'
301 16
                        && isset($this->pattern[$offset + $length + 1])
302
                    ) {
303
                        // if pattern starts from optional params, put slash at the end of param pattern
304
                        // @see https://github.com/yiisoft/yii2/issues/13086
305 4
                        $appendSlash = true;
306 4
                        $tr["<$name>/"] = "((?P<$placeholder>$pattern)/)?";
307
                    } elseif (
308 16
                        $offset > 1
309 16
                        && $this->pattern[$offset - 1] === '/'
310 16
                        && (!isset($this->pattern[$offset + $length]) || $this->pattern[$offset + $length] === '/')
311
                    ) {
312 8
                        $appendSlash = false;
313 8
                        $tr["/<$name>"] = "(/(?P<$placeholder>$pattern))?";
314
                    }
315 16
                    $tr["<$name>"] = "(?P<$placeholder>$pattern)?";
316 16
                    $oldOffset = $offset + $length;
317
                } else {
318 89
                    $appendSlash = false;
319 89
                    $tr["<$name>"] = "(?P<$placeholder>$pattern)";
320
                }
321
322 89
                if (isset($this->_routeParams[$name])) {
323 16
                    $tr2["<$name>"] = "(?P<$placeholder>$pattern)";
324
                } else {
325 89
                    $this->_paramRules[$name] = $pattern === '[^\/]+' ? '' : "#^$pattern$#u";
326
                }
327
            }
328
        }
329
330
        // we have only optional params in route - ensure slash position on param patterns
331 91
        if ($allowAppendSlash && trim($requiredPatternPart, '/') === '') {
332 12
            $this->translatePattern(false);
333 12
            return;
334
        }
335
336 91
        $this->_template = preg_replace('/<([\w._-]+):?([^>]+)?>/', '<$1>', $this->pattern);
337 91
        $this->pattern = '#^' . trim(strtr($this->_template, $tr), '/') . '$#u';
338
339
        // if host starts with relative scheme, then insert pattern to match any
340 91
        if ($this->host !== null && strncmp($this->host, '//', 2) === 0) {
341 8
            $this->pattern = substr_replace($this->pattern, '[\w]+://', 2, 0);
0 ignored issues
show
Documentation Bug introduced by
It seems like substr_replace($this->pattern, '[\w]+://', 2, 0) can also be of type array. However, the property $pattern is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
342
        }
343
344 91
        if (!empty($this->_routeParams)) {
345 16
            $this->_routeRule = '#^' . strtr($this->route, $tr2) . '$#u';
346
        }
347
    }
348
349
    /**
350
     * @param UrlManager $manager the URL manager
351
     * @return UrlNormalizer|null
352
     * @since 2.0.10
353
     */
354 16
    protected function getNormalizer($manager)
355
    {
356 16
        if ($this->normalizer === null) {
357 15
            return $manager->normalizer;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $manager->normalizer also could return the type array|boolean|string which is incompatible with the documented return type null|yii\web\UrlNormalizer.
Loading history...
358
        }
359
360 1
        return $this->normalizer;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->normalizer also could return the type array|boolean which is incompatible with the documented return type null|yii\web\UrlNormalizer.
Loading history...
361
    }
362
363
    /**
364
     * @param UrlManager $manager the URL manager
365
     * @return bool
366
     * @since 2.0.10
367
     */
368 16
    protected function hasNormalizer($manager)
369
    {
370 16
        return $this->getNormalizer($manager) instanceof UrlNormalizer;
371
    }
372
373
    /**
374
     * Parses the given request and returns the corresponding route and parameters.
375
     * @param UrlManager $manager the URL manager
376
     * @param Request $request the request component
377
     * @return array|bool the parsing result. The route and the parameters are returned as an array.
378
     * If `false`, it means this rule cannot be used to parse this path info.
379
     */
380 16
    public function parseRequest($manager, $request)
381
    {
382 16
        if ($this->mode === self::CREATION_ONLY) {
383 3
            return false;
384
        }
385
386 16
        if (!empty($this->verb) && !in_array($request->getMethod(), $this->verb, true)) {
0 ignored issues
show
Bug introduced by
It seems like $this->verb can also be of type string; however, parameter $haystack of in_array() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

386
        if (!empty($this->verb) && !in_array($request->getMethod(), /** @scrutinizer ignore-type */ $this->verb, true)) {
Loading history...
387 2
            return false;
388
        }
389
390 16
        $suffix = (string) ($this->suffix === null ? $manager->suffix : $this->suffix);
391 16
        $pathInfo = $request->getPathInfo();
392 16
        $normalized = false;
393 16
        if ($this->hasNormalizer($manager)) {
394 4
            $pathInfo = $this->getNormalizer($manager)->normalizePathInfo($pathInfo, $suffix, $normalized);
395
        }
396 16
        if ($suffix !== '' && $pathInfo !== '') {
397 9
            $n = strlen($suffix);
398 9
            if (substr_compare($pathInfo, $suffix, -$n, $n) === 0) {
399 9
                $pathInfo = substr($pathInfo, 0, -$n);
400 9
                if ($pathInfo === '') {
401
                    // suffix alone is not allowed
402 9
                    return false;
403
                }
404
            } else {
405 8
                return false;
406
            }
407
        }
408
409 16
        if ($this->host !== null) {
410 3
            $pathInfo = strtolower($request->getHostInfo()) . ($pathInfo === '' ? '' : '/' . $pathInfo);
0 ignored issues
show
Bug introduced by
It seems like $request->getHostInfo() can also be of type null; however, parameter $string of strtolower() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

410
            $pathInfo = strtolower(/** @scrutinizer ignore-type */ $request->getHostInfo()) . ($pathInfo === '' ? '' : '/' . $pathInfo);
Loading history...
411
        }
412
413 16
        if (!preg_match($this->pattern, $pathInfo, $matches)) {
414 15
            return false;
415
        }
416 16
        $matches = $this->substitutePlaceholderNames($matches);
417
418 16
        foreach ($this->defaults as $name => $value) {
419 3
            if (!isset($matches[$name]) || $matches[$name] === '') {
420 3
                $matches[$name] = $value;
421
            }
422
        }
423 16
        $params = $this->defaults;
424 16
        $tr = [];
425 16
        foreach ($matches as $name => $value) {
426 16
            if (isset($this->_routeParams[$name])) {
427 4
                $tr[$this->_routeParams[$name]] = $value;
428 4
                unset($params[$name]);
429 16
            } elseif (isset($this->_paramRules[$name])) {
430 15
                $params[$name] = $value;
431
            }
432
        }
433 16
        if ($this->_routeRule !== null) {
434 4
            $route = strtr($this->route, $tr);
435
        } else {
436 16
            $route = $this->route;
437
        }
438
439 16
        Yii::debug("Request parsed with URL rule: {$this->name}", __METHOD__);
440
441 16
        if ($normalized) {
442
            // pathInfo was changed by normalizer - we need also normalize route
443 4
            return $this->getNormalizer($manager)->normalizeRoute([$route, $params]);
444
        }
445
446 14
        return [$route, $params];
447
    }
448
449
    /**
450
     * Creates a URL according to the given route and parameters.
451
     * @param UrlManager $manager the URL manager
452
     * @param string $route the route. It should not have slashes at the beginning or the end.
453
     * @param array $params the parameters
454
     * @return string|bool the created URL, or `false` if this rule cannot be used for creating this URL.
455
     */
456 78
    public function createUrl($manager, $route, $params)
457
    {
458 78
        if ($this->mode === self::PARSING_ONLY) {
459 3
            $this->createStatus = self::CREATE_STATUS_PARSING_ONLY;
460 3
            return false;
461
        }
462
463 77
        $tr = [];
464
465
        // match the route part first
466 77
        if ($route !== $this->route) {
467 64
            if ($this->_routeRule !== null && preg_match($this->_routeRule, $route, $matches)) {
468 12
                $matches = $this->substitutePlaceholderNames($matches);
469 12
                foreach ($this->_routeParams as $name => $token) {
470 12
                    if (isset($this->defaults[$name]) && strcmp($this->defaults[$name], $matches[$name]) === 0) {
471 1
                        $tr[$token] = '';
472
                    } else {
473 12
                        $tr[$token] = $matches[$name];
474
                    }
475
                }
476
            } else {
477 63
                $this->createStatus = self::CREATE_STATUS_ROUTE_MISMATCH;
478 63
                return false;
479
            }
480
        }
481
482
        // match default params
483
        // if a default param is not in the route pattern, its value must also be matched
484 77
        foreach ($this->defaults as $name => $value) {
485 15
            if (isset($this->_routeParams[$name])) {
486 1
                continue;
487
            }
488 15
            if (!isset($params[$name])) {
489
                // allow omit empty optional params
490
                // @see https://github.com/yiisoft/yii2/issues/10970
491 10
                if (in_array($name, $this->placeholders) && strcmp($value, '') === 0) {
492 1
                    $params[$name] = '';
493
                } else {
494 10
                    $this->createStatus = self::CREATE_STATUS_PARAMS_MISMATCH;
495 10
                    return false;
496
                }
497
            }
498 15
            if (strcmp($params[$name], $value) === 0) { // strcmp will do string conversion automatically
499 15
                unset($params[$name]);
500 15
                if (isset($this->_paramRules[$name])) {
501 15
                    $tr["<$name>"] = '';
502
                }
503 14
            } elseif (!isset($this->_paramRules[$name])) {
504 13
                $this->createStatus = self::CREATE_STATUS_PARAMS_MISMATCH;
505 13
                return false;
506
            }
507
        }
508
509
        // match params in the pattern
510 77
        foreach ($this->_paramRules as $name => $rule) {
511 69
            if (isset($params[$name]) && !is_array($params[$name]) && ($rule === '' || preg_match($rule, $params[$name]))) {
512 67
                $tr["<$name>"] = $this->encodeParams ? urlencode($params[$name]) : $params[$name];
513 67
                unset($params[$name]);
514 56
            } elseif (!isset($this->defaults[$name]) || isset($params[$name])) {
515 55
                $this->createStatus = self::CREATE_STATUS_PARAMS_MISMATCH;
516 55
                return false;
517
            }
518
        }
519
520 77
        $url = $this->trimSlashes(strtr($this->_template, $tr));
521 77
        if ($this->host !== null) {
522 13
            $pos = strpos($url, '/', 8);
523 13
            if ($pos !== false) {
524 13
                $url = substr($url, 0, $pos) . preg_replace('#/+#', '/', substr($url, $pos));
525
            }
526 65
        } elseif (strpos($url, '//') !== false) {
527 11
            $url = preg_replace('#/+#', '/', trim($url, '/'));
528
        }
529
530 77
        if ($url !== '') {
531 69
            $url .= ($this->suffix === null ? $manager->suffix : $this->suffix);
532
        }
533
534 77
        if (!empty($params) && ($query = http_build_query($params)) !== '') {
535 55
            $url .= '?' . $query;
536
        }
537
538 77
        $this->createStatus = self::CREATE_STATUS_SUCCESS;
539 77
        return $url;
540
    }
541
542
    /**
543
     * Returns status of the URL creation after the last [[createUrl()]] call.
544
     *
545
     * @return int|null Status of the URL creation after the last [[createUrl()]] call. `null` if rule does not provide
546
     * info about create status.
547
     * @see createStatus
548
     * @since 2.0.12
549
     */
550 77
    public function getCreateUrlStatus()
551
    {
552 77
        return $this->createStatus;
553
    }
554
555
    /**
556
     * Returns list of regex for matching parameter.
557
     * @return array parameter keys and regexp rules.
558
     *
559
     * @since 2.0.6
560
     */
561
    protected function getParamRules()
562
    {
563
        return $this->_paramRules;
564
    }
565
566
    /**
567
     * Iterates over [[placeholders]] and checks whether each placeholder exists as a key in $matches array.
568
     * When found - replaces this placeholder key with a appropriate name of matching parameter.
569
     * Used in [[parseRequest()]], [[createUrl()]].
570
     *
571
     * @param array $matches result of `preg_match()` call
572
     * @return array input array with replaced placeholder keys
573
     * @see placeholders
574
     * @since 2.0.7
575
     */
576 28
    protected function substitutePlaceholderNames(array $matches)
577
    {
578 28
        foreach ($this->placeholders as $placeholder => $name) {
579 27
            if (isset($matches[$placeholder])) {
580 27
                $matches[$name] = $matches[$placeholder];
581 27
                unset($matches[$placeholder]);
582
            }
583
        }
584
585 28
        return $matches;
586
    }
587
588
    /**
589
     * Trim slashes in passed string. If string begins with '//', two slashes are left as is
590
     * in the beginning of a string.
591
     *
592
     * @param string $string
593
     * @return string
594
     */
595 101
    private function trimSlashes($string)
596
    {
597 101
        if (strncmp($string, '//', 2) === 0) {
598 16
            return '//' . trim($string, '/');
599
        }
600
601 101
        return trim($string, '/');
602
    }
603
}
604