Completed
Push — master ( 21faee...97cad1 )
by Dmitry
20:25
created

UrlRule   D

Complexity

Total Complexity 88

Size/Duplication

Total Lines 421
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 96.5%

Importance

Changes 0
Metric Value
wmc 88
lcom 1
cbo 6
dl 0
loc 421
ccs 193
cts 200
cp 0.965
rs 4.8717
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
F init() 0 98 29
A getNormalizer() 0 8 2
A hasNormalizer() 0 4 1
F parseRequest() 0 68 21
F createUrl() 0 79 31
A getParamRules() 0 4 1
A substitutePlaceholderNames() 0 10 3

How to fix   Complexity   

Complex Class

Complex classes like UrlRule often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use UrlRule, and based on these observations, apply Extract Interface, too.

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, 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
    /**
131
     * Initializes this rule.
132
     */
133 29
    public function init()
134
    {
135 29
        if ($this->pattern === null) {
136
            throw new InvalidConfigException('UrlRule::pattern must be set.');
137
        }
138 29
        if ($this->route === null) {
139
            throw new InvalidConfigException('UrlRule::route must be set.');
140
        }
141 29
        if (is_array($this->normalizer)) {
142 1
            $normalizerConfig = array_merge(['class' => UrlNormalizer::className()], $this->normalizer);
143 1
            $this->normalizer = Yii::createObject($normalizerConfig);
144 1
        }
145 29
        if ($this->normalizer !== null && $this->normalizer !== false && !$this->normalizer instanceof UrlNormalizer) {
146
            throw new InvalidConfigException('Invalid config for UrlRule::normalizer.');
147
        }
148 29
        if ($this->verb !== null) {
149 10
            if (is_array($this->verb)) {
150 10
                foreach ($this->verb as $i => $verb) {
151 10
                    $this->verb[$i] = strtoupper($verb);
152 10
                }
153 10
            } else {
154
                $this->verb = [strtoupper($this->verb)];
155
            }
156 10
        }
157 29
        if ($this->name === null) {
158 29
            $this->name = $this->pattern;
159 29
        }
160
161 29
        $this->pattern = trim($this->pattern, '/');
162 29
        $this->route = trim($this->route, '/');
163
164 29
        if ($this->host !== null) {
165 9
            $this->host = rtrim($this->host, '/');
166 9
            $this->pattern = rtrim($this->host . '/' . $this->pattern, '/');
167 29
        } elseif ($this->pattern === '') {
168 6
            $this->_template = '';
169 6
            $this->pattern = '#^$#u';
170
171 6
            return;
172 24
        } elseif (($pos = strpos($this->pattern, '://')) !== false) {
173 6
            if (($pos2 = strpos($this->pattern, '/', $pos + 3)) !== false) {
174 6
                $this->host = substr($this->pattern, 0, $pos2);
175 6
            } else {
176
                $this->host = $this->pattern;
177
            }
178 6
        } else {
179 22
            $this->pattern = '/' . $this->pattern . '/';
180
        }
181
182 28
        if (strpos($this->route, '<') !== false && preg_match_all('/<([\w._-]+)>/', $this->route, $matches)) {
183 5
            foreach ($matches[1] as $name) {
184 5
                $this->_routeParams[$name] = "<$name>";
185 5
            }
186 5
        }
187
188
        $tr = [
189 28
            '.' => '\\.',
190 28
            '*' => '\\*',
191 28
            '$' => '\\$',
192 28
            '[' => '\\[',
193 28
            ']' => '\\]',
194 28
            '(' => '\\(',
195 28
            ')' => '\\)',
196 28
        ];
197
198 28
        $tr2 = [];
199 28
        if (preg_match_all('/<([\w._-]+):?([^>]+)?>/', $this->pattern, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
200 24
            foreach ($matches as $match) {
201 24
                $name = $match[1][0];
202 24
                $pattern = isset($match[2][0]) ? $match[2][0] : '[^\/]+';
203 24
                $placeholder = 'a' . hash('crc32b', $name); // placeholder must begin with a letter
204 24
                $this->placeholders[$placeholder] = $name;
205 24
                if (array_key_exists($name, $this->defaults)) {
206 4
                    $length = strlen($match[0][0]);
207 4
                    $offset = $match[0][1];
208 4
                    if ($offset > 1 && $this->pattern[$offset - 1] === '/' && (!isset($this->pattern[$offset + $length]) || $this->pattern[$offset + $length] === '/')) {
209 4
                        $tr["/<$name>"] = "(/(?P<$placeholder>$pattern))?";
210 4
                    } else {
211 4
                        $tr["<$name>"] = "(?P<$placeholder>$pattern)?";
212
                    }
213 4
                } else {
214 24
                    $tr["<$name>"] = "(?P<$placeholder>$pattern)";
215
                }
216 24
                if (isset($this->_routeParams[$name])) {
217 5
                    $tr2["<$name>"] = "(?P<$placeholder>$pattern)";
218 5
                } else {
219 24
                    $this->_paramRules[$name] = $pattern === '[^\/]+' ? '' : "#^$pattern$#u";
220
                }
221 24
            }
222 24
        }
223
224 28
        $this->_template = preg_replace('/<([\w._-]+):?([^>]+)?>/', '<$1>', $this->pattern);
225 28
        $this->pattern = '#^' . trim(strtr($this->_template, $tr), '/') . '$#u';
226
227 28
        if (!empty($this->_routeParams)) {
228 5
            $this->_routeRule = '#^' . strtr($this->route, $tr2) . '$#u';
229 5
        }
230 28
    }
231
232
    /**
233
     * @param UrlManager $manager the URL manager
234
     * @return UrlNormalizer|null
235
     * @since 2.0.10
236
     */
237 9
    protected function getNormalizer($manager)
238
    {
239 9
        if ($this->normalizer === null) {
240 8
            return $manager->normalizer;
241
        } else {
242 1
            return $this->normalizer;
243
        }
244
    }
245
246
    /**
247
     * @param UrlManager $manager the URL manager
248
     * @return bool
249
     * @since 2.0.10
250
     */
251 9
    protected function hasNormalizer($manager)
252
    {
253 9
        return $this->getNormalizer($manager) instanceof UrlNormalizer;
254
    }
255
256
    /**
257
     * Parses the given request and returns the corresponding route and parameters.
258
     * @param UrlManager $manager the URL manager
259
     * @param Request $request the request component
260
     * @return array|bool the parsing result. The route and the parameters are returned as an array.
261
     * If `false`, it means this rule cannot be used to parse this path info.
262
     */
263 9
    public function parseRequest($manager, $request)
264
    {
265 9
        if ($this->mode === self::CREATION_ONLY) {
266 3
            return false;
267
        }
268
269 9
        if (!empty($this->verb) && !in_array($request->getMethod(), $this->verb, true)) {
270 2
            return false;
271
        }
272
273 9
        $suffix = (string)($this->suffix === null ? $manager->suffix : $this->suffix);
274 9
        $pathInfo = $request->getPathInfo();
275 9
        $normalized = false;
276 9
        if ($this->hasNormalizer($manager)) {
277 4
            $pathInfo = $this->getNormalizer($manager)->normalizePathInfo($pathInfo, $suffix, $normalized);
278 4
        }
279 9
        if ($suffix !== '' && $pathInfo !== '') {
280 6
            $n = strlen($suffix);
281 6
            if (substr_compare($pathInfo, $suffix, -$n, $n) === 0) {
282 6
                $pathInfo = substr($pathInfo, 0, -$n);
283 6
                if ($pathInfo === '') {
284
                    // suffix alone is not allowed
285 3
                    return false;
286
                }
287 6
            } else {
288 5
                return false;
289
            }
290 6
        }
291
292 9
        if ($this->host !== null) {
293 3
            $pathInfo = strtolower($request->getHostInfo()) . ($pathInfo === '' ? '' : '/' . $pathInfo);
294 3
        }
295
296 9
        if (!preg_match($this->pattern, $pathInfo, $matches)) {
297 9
            return false;
298
        }
299 9
        $matches = $this->substitutePlaceholderNames($matches);
300
301 9
        foreach ($this->defaults as $name => $value) {
302 3
            if (!isset($matches[$name]) || $matches[$name] === '') {
303 3
                $matches[$name] = $value;
304 3
            }
305 9
        }
306 9
        $params = $this->defaults;
307 9
        $tr = [];
308 9
        foreach ($matches as $name => $value) {
309 9
            if (isset($this->_routeParams[$name])) {
310 3
                $tr[$this->_routeParams[$name]] = $value;
311 3
                unset($params[$name]);
312 9
            } elseif (isset($this->_paramRules[$name])) {
313 8
                $params[$name] = $value;
314 8
            }
315 9
        }
316 9
        if ($this->_routeRule !== null) {
317 3
            $route = strtr($this->route, $tr);
318 3
        } else {
319 9
            $route = $this->route;
320
        }
321
322 9
        Yii::trace("Request parsed with URL rule: {$this->name}", __METHOD__);
323
324 9
        if ($normalized) {
325
            // pathInfo was changed by normalizer - we need also normalize route
326 4
            return $this->getNormalizer($manager)->normalizeRoute([$route, $params]);
327
        } else {
328 8
            return [$route, $params];
329
        }
330
    }
331
332
    /**
333
     * Creates a URL according to the given route and parameters.
334
     * @param UrlManager $manager the URL manager
335
     * @param string $route the route. It should not have slashes at the beginning or the end.
336
     * @param array $params the parameters
337
     * @return string|bool the created URL, or `false` if this rule cannot be used for creating this URL.
338
     */
339 20
    public function createUrl($manager, $route, $params)
340
    {
341 20
        if ($this->mode === self::PARSING_ONLY) {
342 9
            return false;
343
        }
344
345 20
        $tr = [];
346
347
        // match the route part first
348 20
        if ($route !== $this->route) {
349 12
            if ($this->_routeRule !== null && preg_match($this->_routeRule, $route, $matches)) {
350 2
                $matches = $this->substitutePlaceholderNames($matches);
351 2
                foreach ($this->_routeParams as $name => $token) {
352 2
                    if (isset($this->defaults[$name]) && strcmp($this->defaults[$name], $matches[$name]) === 0) {
353 1
                        $tr[$token] = '';
354 1
                    } else {
355 2
                        $tr[$token] = $matches[$name];
356
                    }
357 2
                }
358 2
            } else {
359 12
                return false;
360
            }
361 2
        }
362
363
        // match default params
364
        // if a default param is not in the route pattern, its value must also be matched
365 19
        foreach ($this->defaults as $name => $value) {
366 6
            if (isset($this->_routeParams[$name])) {
367 1
                continue;
368
            }
369 6
            if (!isset($params[$name])) {
370
                // allow omit empty optional params
371
                // @see https://github.com/yiisoft/yii2/issues/10970
372 1
                if (in_array($name, $this->placeholders) && strcmp($value, '') === 0) {
373 1
                    $params[$name] = '';
374 1
                } else {
375 1
                    return false;
376
                }
377 1
            }
378 6
            if (strcmp($params[$name], $value) === 0) { // strcmp will do string conversion automatically
379 6
                unset($params[$name]);
380 6
                if (isset($this->_paramRules[$name])) {
381 1
                    $tr["<$name>"] = '';
382 1
                }
383 6
            } elseif (!isset($this->_paramRules[$name])) {
384 6
                return false;
385
            }
386 19
        }
387
388
        // match params in the pattern
389 19
        foreach ($this->_paramRules as $name => $rule) {
390 15
            if (isset($params[$name]) && !is_array($params[$name]) && ($rule === '' || preg_match($rule, $params[$name]))) {
391 14
                $tr["<$name>"] = $this->encodeParams ? urlencode($params[$name]) : $params[$name];
392 14
                unset($params[$name]);
393 15
            } elseif (!isset($this->defaults[$name]) || isset($params[$name])) {
394 10
                return false;
395
            }
396 19
        }
397
398 19
        $url = trim(strtr($this->_template, $tr), '/');
399 19
        if ($this->host !== null) {
400 8
            $pos = strpos($url, '/', 8);
401 8
            if ($pos !== false) {
402 8
                $url = substr($url, 0, $pos) . preg_replace('#/+#', '/', substr($url, $pos));
403 8
            }
404 19
        } elseif (strpos($url, '//') !== false) {
405 1
            $url = preg_replace('#/+#', '/', $url);
406 1
        }
407
408 19
        if ($url !== '') {
409 18
            $url .= ($this->suffix === null ? $manager->suffix : $this->suffix);
410 18
        }
411
412 19
        if (!empty($params) && ($query = http_build_query($params)) !== '') {
413 12
            $url .= '?' . $query;
414 12
        }
415
416 19
        return $url;
417
    }
418
419
    /**
420
     * Returns list of regex for matching parameter.
421
     * @return array parameter keys and regexp rules.
422
     *
423
     * @since 2.0.6
424
     */
425
    protected function getParamRules()
426
    {
427
        return $this->_paramRules;
428
    }
429
430
    /**
431
     * Iterates over [[placeholders]] and checks whether each placeholder exists as a key in $matches array.
432
     * When found - replaces this placeholder key with a appropriate name of matching parameter.
433
     * Used in [[parseRequest()]], [[createUrl()]].
434
     *
435
     * @param array $matches result of `preg_match()` call
436
     * @return array input array with replaced placeholder keys
437
     * @see placeholders
438
     * @since 2.0.7
439
     */
440 11
    protected function substitutePlaceholderNames(array $matches)
441
    {
442 11
        foreach ($this->placeholders as $placeholder => $name) {
443 10
            if (isset($matches[$placeholder])) {
444 10
                $matches[$name] = $matches[$placeholder];
445 10
                unset($matches[$placeholder]);
446 10
            }
447 11
        }
448 11
        return $matches;
449
    }
450
}
451