Completed
Push — master ( 1e4484...81bdf8 )
by Carsten
12:10
created

UrlRule::trimSlashes()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 2
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\Object;
12
use yii\base\InvalidConfigException;
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
    /**
42
     * @var string the name of this rule. If not set, it will use [[pattern]] as the name.
43
     */
44
    public $name;
45
    /**
46
     * On the rule initialization, the [[pattern]] matching parameters names will be replaced with [[placeholders]].
47
     * @var string the pattern used to parse and create the path info part of a URL.
48
     * @see host
49
     * @see placeholders
50
     */
51
    public $pattern;
52
    /**
53
     * @var string the pattern used to parse and create the host info part of a URL (e.g. `http://example.com`).
54
     * @see pattern
55
     */
56
    public $host;
57
    /**
58
     * @var string the route to the controller action
59
     */
60
    public $route;
61
    /**
62
     * @var array the default GET parameters (name => value) that this rule provides.
63
     * When this rule is used to parse the incoming request, the values declared in this property
64
     * will be injected into $_GET.
65
     */
66
    public $defaults = [];
67
    /**
68
     * @var string the URL suffix used for this rule.
69
     * For example, ".html" can be used so that the URL looks like pointing to a static HTML page.
70
     * If not set, the value of [[UrlManager::suffix]] will be used.
71
     */
72
    public $suffix;
73
    /**
74
     * @var string|array the HTTP verb (e.g. GET, POST, DELETE) that this rule should match.
75
     * Use array to represent multiple verbs that this rule may match.
76
     * If this property is not set, the rule can match any verb.
77
     * Note that this property is only used when parsing a request. It is ignored for URL creation.
78
     */
79
    public $verb;
80
    /**
81
     * @var int a value indicating if this rule should be used for both request parsing and URL creation,
82
     * parsing only, or creation only.
83
     * If not set or 0, it means the rule is both request parsing and URL creation.
84
     * If it is [[PARSING_ONLY]], the rule is for request parsing only.
85
     * If it is [[CREATION_ONLY]], the rule is for URL creation only.
86
     */
87
    public $mode;
88
    /**
89
     * @var bool a value indicating if parameters should be url encoded.
90
     */
91
    public $encodeParams = true;
92
    /**
93
     * @var UrlNormalizer|array|false|null the configuration for [[UrlNormalizer]] used by this rule.
94
     * If `null`, [[UrlManager::normalizer]] will be used, if `false`, normalization will be skipped
95
     * for this rule.
96
     * @since 2.0.10
97
     */
98
    public $normalizer;
99
100
    /**
101
     * @var array list of placeholders for matching parameters names. Used in [[parseRequest()]], [[createUrl()]].
102
     * On the rule initialization, the [[pattern]] parameters names will be replaced with placeholders.
103
     * This array contains relations between the original parameters names and their placeholders.
104
     * The array keys are the placeholders and the values are the original names.
105
     *
106
     * @see parseRequest()
107
     * @see createUrl()
108
     * @since 2.0.7
109
     */
110
    protected $placeholders = [];
111
112
    /**
113
     * @var string the template for generating a new URL. This is derived from [[pattern]] and is used in generating URL.
114
     */
115
    private $_template;
116
    /**
117
     * @var string the regex for matching the route part. This is used in generating URL.
118
     */
119
    private $_routeRule;
120
    /**
121
     * @var array list of regex for matching parameters. This is used in generating URL.
122
     */
123
    private $_paramRules = [];
124
    /**
125
     * @var array list of parameters used in the route.
126
     */
127
    private $_routeParams = [];
128
129
    /**
130
     * @return string
131
     * @since 2.0.11
132
     */
133 12
    public function __toString()
134
    {
135 12
        $str = '';
136 12
        if ($this->verb !== null) {
137 3
            $str .= implode(',', $this->verb) . ' ';
138 3
        }
139 12
        if ($this->host !== null && strrpos($this->name, $this->host) === false) {
140 1
            $str .= $this->host . '/';
141 1
        }
142 12
        $str .= $this->name;
143
144 12
        if ($str === '') {
145 1
            return '/';
146
        }
147 12
        return $str;
148
    }
149
150
    /**
151
     * Initializes this rule.
152
     */
153 87
    public function init()
154
    {
155 87
        if ($this->pattern === null) {
156
            throw new InvalidConfigException('UrlRule::pattern must be set.');
157
        }
158 87
        if ($this->route === null) {
159
            throw new InvalidConfigException('UrlRule::route must be set.');
160
        }
161 87
        if (is_array($this->normalizer)) {
162 1
            $normalizerConfig = array_merge(['class' => UrlNormalizer::className()], $this->normalizer);
163 1
            $this->normalizer = Yii::createObject($normalizerConfig);
164 1
        }
165 87
        if ($this->normalizer !== null && $this->normalizer !== false && !$this->normalizer instanceof UrlNormalizer) {
166
            throw new InvalidConfigException('Invalid config for UrlRule::normalizer.');
167
        }
168 87
        if ($this->verb !== null) {
169 11
            if (is_array($this->verb)) {
170 11
                foreach ($this->verb as $i => $verb) {
171 11
                    $this->verb[$i] = strtoupper($verb);
172 11
                }
173 11
            } else {
174
                $this->verb = [strtoupper($this->verb)];
175
            }
176 11
        }
177 87
        if ($this->name === null) {
178 87
            $this->name = $this->pattern;
179 87
        }
180
181 87
        $this->pattern = $this->trimSlashes($this->pattern);
182 87
        $this->route = trim($this->route, '/');
183
184 87
        if ($this->host !== null) {
185 17
            $this->host = rtrim($this->host, '/');
186 17
            $this->pattern = rtrim($this->host . '/' . $this->pattern, '/');
187 87
        } elseif ($this->pattern === '') {
188 21
            $this->_template = '';
189 21
            $this->pattern = '#^$#u';
190
191 21
            return;
192 75
        } elseif (($pos = strpos($this->pattern, '://')) !== false) {
193 9
            if (($pos2 = strpos($this->pattern, '/', $pos + 3)) !== false) {
194 9
                $this->host = substr($this->pattern, 0, $pos2);
195 9
            } else {
196
                $this->host = $this->pattern;
197
            }
198 75
        } elseif (strpos($this->pattern, '//') === 0) {
199 8
            if (($pos2 = strpos($this->pattern, '/', $pos + 2)) !== false) {
200 8
                $this->host = substr($this->pattern, 0, $pos2);
201 8
            } else {
202 4
                $this->host = $this->pattern;
203
            }
204 8
        } else {
205 67
            $this->pattern = '/' . $this->pattern . '/';
206
        }
207
208 79
        if (strpos($this->route, '<') !== false && preg_match_all('/<([\w._-]+)>/', $this->route, $matches)) {
209 13
            foreach ($matches[1] as $name) {
210 13
                $this->_routeParams[$name] = "<$name>";
211 13
            }
212 13
        }
213
214
        $tr = [
215 79
            '.' => '\\.',
216 79
            '*' => '\\*',
217 79
            '$' => '\\$',
218 79
            '[' => '\\[',
219 79
            ']' => '\\]',
220 79
            '(' => '\\(',
221 79
            ')' => '\\)',
222 79
        ];
223
224 79
        $tr2 = [];
225 79
        if (preg_match_all('/<([\w._-]+):?([^>]+)?>/', $this->pattern, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
226 77
            foreach ($matches as $match) {
227 77
                $name = $match[1][0];
228 77
                $pattern = isset($match[2][0]) ? $match[2][0] : '[^\/]+';
229 77
                $placeholder = 'a' . hash('crc32b', $name); // placeholder must begin with a letter
230 77
                $this->placeholders[$placeholder] = $name;
231 77
                if (array_key_exists($name, $this->defaults)) {
232 5
                    $length = strlen($match[0][0]);
233 5
                    $offset = $match[0][1];
234 5
                    if ($offset > 1 && $this->pattern[$offset - 1] === '/' && (!isset($this->pattern[$offset + $length]) || $this->pattern[$offset + $length] === '/')) {
235 5
                        $tr["/<$name>"] = "(/(?P<$placeholder>$pattern))?";
236 5
                    } else {
237 4
                        $tr["<$name>"] = "(?P<$placeholder>$pattern)?";
238
                    }
239 5
                } else {
240 77
                    $tr["<$name>"] = "(?P<$placeholder>$pattern)";
241
                }
242 77
                if (isset($this->_routeParams[$name])) {
243 13
                    $tr2["<$name>"] = "(?P<$placeholder>$pattern)";
244 13
                } else {
245 77
                    $this->_paramRules[$name] = $pattern === '[^\/]+' ? '' : "#^$pattern$#u";
246
                }
247 77
            }
248 77
        }
249
250 79
        $this->_template = preg_replace('/<([\w._-]+):?([^>]+)?>/', '<$1>', $this->pattern);
251 79
        $this->pattern = '#^' . trim(strtr($this->_template, $tr), '/') . '$#u';
252
253
        // if host starts with relative scheme, then insert pattern to match any
254 79
        if (strpos($this->host, '//') === 0) {
255 8
            $this->pattern = substr_replace($this->pattern, '[\w]+://', 2, 0);
256 8
        }
257
258 79
        if (!empty($this->_routeParams)) {
259 13
            $this->_routeRule = '#^' . strtr($this->route, $tr2) . '$#u';
260 13
        }
261 79
    }
262
263
    /**
264
     * @param UrlManager $manager the URL manager
265
     * @return UrlNormalizer|null
266
     * @since 2.0.10
267
     */
268 15
    protected function getNormalizer($manager)
269
    {
270 15
        if ($this->normalizer === null) {
271 14
            return $manager->normalizer;
272
        } else {
273 1
            return $this->normalizer;
274
        }
275
    }
276
277
    /**
278
     * @param UrlManager $manager the URL manager
279
     * @return bool
280
     * @since 2.0.10
281
     */
282 15
    protected function hasNormalizer($manager)
283
    {
284 15
        return $this->getNormalizer($manager) instanceof UrlNormalizer;
285
    }
286
287
    /**
288
     * Parses the given request and returns the corresponding route and parameters.
289
     * @param UrlManager $manager the URL manager
290
     * @param Request $request the request component
291
     * @return array|bool the parsing result. The route and the parameters are returned as an array.
292
     * If `false`, it means this rule cannot be used to parse this path info.
293
     */
294 15
    public function parseRequest($manager, $request)
295
    {
296 15
        if ($this->mode === self::CREATION_ONLY) {
297 3
            return false;
298
        }
299
300 15
        if (!empty($this->verb) && !in_array($request->getMethod(), $this->verb, true)) {
301 2
            return false;
302
        }
303
304 15
        $suffix = (string)($this->suffix === null ? $manager->suffix : $this->suffix);
305 15
        $pathInfo = $request->getPathInfo();
306 15
        $normalized = false;
307 15
        if ($this->hasNormalizer($manager)) {
308 4
            $pathInfo = $this->getNormalizer($manager)->normalizePathInfo($pathInfo, $suffix, $normalized);
309 4
        }
310 15
        if ($suffix !== '' && $pathInfo !== '') {
311 9
            $n = strlen($suffix);
312 9
            if (substr_compare($pathInfo, $suffix, -$n, $n) === 0) {
313 9
                $pathInfo = substr($pathInfo, 0, -$n);
314 9
                if ($pathInfo === '') {
315
                    // suffix alone is not allowed
316 3
                    return false;
317
                }
318 9
            } else {
319 8
                return false;
320
            }
321 9
        }
322
323 15
        if ($this->host !== null) {
324 3
            $pathInfo = strtolower($request->getHostInfo()) . ($pathInfo === '' ? '' : '/' . $pathInfo);
325 3
        }
326
327 15
        if (!preg_match($this->pattern, $pathInfo, $matches)) {
328 14
            return false;
329
        }
330 15
        $matches = $this->substitutePlaceholderNames($matches);
331
332 15
        foreach ($this->defaults as $name => $value) {
333 3
            if (!isset($matches[$name]) || $matches[$name] === '') {
334 3
                $matches[$name] = $value;
335 3
            }
336 15
        }
337 15
        $params = $this->defaults;
338 15
        $tr = [];
339 15
        foreach ($matches as $name => $value) {
340 15
            if (isset($this->_routeParams[$name])) {
341 3
                $tr[$this->_routeParams[$name]] = $value;
342 3
                unset($params[$name]);
343 15
            } elseif (isset($this->_paramRules[$name])) {
344 14
                $params[$name] = $value;
345 14
            }
346 15
        }
347 15
        if ($this->_routeRule !== null) {
348 3
            $route = strtr($this->route, $tr);
349 3
        } else {
350 15
            $route = $this->route;
351
        }
352
353 15
        Yii::trace("Request parsed with URL rule: {$this->name}", __METHOD__);
354
355 15
        if ($normalized) {
356
            // pathInfo was changed by normalizer - we need also normalize route
357 4
            return $this->getNormalizer($manager)->normalizeRoute([$route, $params]);
358
        } else {
359 13
            return [$route, $params];
360
        }
361
    }
362
363
    /**
364
     * Creates a URL according to the given route and parameters.
365
     * @param UrlManager $manager the URL manager
366
     * @param string $route the route. It should not have slashes at the beginning or the end.
367
     * @param array $params the parameters
368
     * @return string|bool the created URL, or `false` if this rule cannot be used for creating this URL.
369
     */
370 71
    public function createUrl($manager, $route, $params)
371
    {
372 71
        if ($this->mode === self::PARSING_ONLY) {
373 9
            return false;
374
        }
375
376 71
        $tr = [];
377
378
        // match the route part first
379 71
        if ($route !== $this->route) {
380 43
            if ($this->_routeRule !== null && preg_match($this->_routeRule, $route, $matches)) {
381 10
                $matches = $this->substitutePlaceholderNames($matches);
382 10
                foreach ($this->_routeParams as $name => $token) {
383 10
                    if (isset($this->defaults[$name]) && strcmp($this->defaults[$name], $matches[$name]) === 0) {
384 1
                        $tr[$token] = '';
385 1
                    } else {
386 10
                        $tr[$token] = $matches[$name];
387
                    }
388 10
                }
389 10
            } else {
390 43
                return false;
391
            }
392 10
        }
393
394
        // match default params
395
        // if a default param is not in the route pattern, its value must also be matched
396 70
        foreach ($this->defaults as $name => $value) {
397 13
            if (isset($this->_routeParams[$name])) {
398 1
                continue;
399
            }
400 13
            if (!isset($params[$name])) {
401
                // allow omit empty optional params
402
                // @see https://github.com/yiisoft/yii2/issues/10970
403 9
                if (in_array($name, $this->placeholders) && strcmp($value, '') === 0) {
404 1
                    $params[$name] = '';
405 1
                } else {
406 9
                    return false;
407
                }
408 1
            }
409 13
            if (strcmp($params[$name], $value) === 0) { // strcmp will do string conversion automatically
410 13
                unset($params[$name]);
411 13
                if (isset($this->_paramRules[$name])) {
412 1
                    $tr["<$name>"] = '';
413 1
                }
414 13
            } elseif (!isset($this->_paramRules[$name])) {
415 13
                return false;
416
            }
417 70
        }
418
419
        // match params in the pattern
420 70
        foreach ($this->_paramRules as $name => $rule) {
421 61
            if (isset($params[$name]) && !is_array($params[$name]) && ($rule === '' || preg_match($rule, $params[$name]))) {
422 60
                $tr["<$name>"] = $this->encodeParams ? urlencode($params[$name]) : $params[$name];
423 60
                unset($params[$name]);
424 61
            } elseif (!isset($this->defaults[$name]) || isset($params[$name])) {
425 49
                return false;
426
            }
427 70
        }
428
429 70
        $url = $this->trimSlashes(strtr($this->_template, $tr));
430 70
        if ($this->host !== null) {
431 13
            $pos = strpos($url, '/', 8);
432 13
            if ($pos !== false) {
433 13
                $url = substr($url, 0, $pos) . preg_replace('#/+#', '/', substr($url, $pos));
434 13
            }
435 70
        } elseif (strpos($url, '//') !== false) {
436 1
            $url = preg_replace('#/+#', '/', $url);
437 1
        }
438
439 70
        if ($url !== '') {
440 62
            $url .= ($this->suffix === null ? $manager->suffix : $this->suffix);
441 62
        }
442
443 70
        if (!empty($params) && ($query = http_build_query($params)) !== '') {
444 51
            $url .= '?' . $query;
445 51
        }
446
447 70
        return $url;
448
    }
449
450
    /**
451
     * Returns list of regex for matching parameter.
452
     * @return array parameter keys and regexp rules.
453
     *
454
     * @since 2.0.6
455
     */
456
    protected function getParamRules()
457
    {
458
        return $this->_paramRules;
459
    }
460
461
    /**
462
     * Iterates over [[placeholders]] and checks whether each placeholder exists as a key in $matches array.
463
     * When found - replaces this placeholder key with a appropriate name of matching parameter.
464
     * Used in [[parseRequest()]], [[createUrl()]].
465
     *
466
     * @param array $matches result of `preg_match()` call
467
     * @return array input array with replaced placeholder keys
468
     * @see placeholders
469
     * @since 2.0.7
470
     */
471 25
    protected function substitutePlaceholderNames(array $matches)
472
    {
473 25
        foreach ($this->placeholders as $placeholder => $name) {
474 24
            if (isset($matches[$placeholder])) {
475 24
                $matches[$name] = $matches[$placeholder];
476 24
                unset($matches[$placeholder]);
477 24
            }
478 25
        }
479 25
        return $matches;
480
    }
481
482
    /**
483
     * Trim slashes in passed string. If string begins with '//', two slashes are left as is
484
     * in the beginning of a string.
485
     *
486
     * @param string $string
487
     * @return string
488
     */
489 87
    private function trimSlashes($string) {
490 87
        if (strpos($string, '//') === 0) {
491 8
            return '//' . trim($string, '/');
492
        }
493 87
        return trim($string, '/');
494
    }
495
}
496