Completed
Push — 2.1 ( c952e8...98ed49 )
by Carsten
10:00
created

UrlRule::createUrl()   F

Complexity

Conditions 29
Paths 1170

Size

Total Lines 72
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 52
CRAP Score 29

Importance

Changes 0
Metric Value
dl 0
loc 72
rs 2.6338
c 0
b 0
f 0
ccs 52
cts 52
cp 1
cc 29
eloc 43
nc 1170
nop 3
crap 29

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
 * @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::class, '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 integer 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 boolean a value indicating if parameters should be url encoded.
90
     */
91
    public $encodeParams = true;
92
93
    /**
94
     * @var array list of placeholders for matching parameters names. Used in [[parseRequest()]], [[createUrl()]].
95
     * On the rule initialization, the [[pattern]] parameters names will be replaced with placeholders.
96
     * This array contains relations between the original parameters names and their placeholders.
97
     * The array keys are the placeholders and the values are the original names.
98
     *
99
     * @see parseRequest()
100
     * @see createUrl()
101
     * @since 2.0.7
102
     */
103
    protected $placeholders = [];
104
105
    /**
106
     * @var string the template for generating a new URL. This is derived from [[pattern]] and is used in generating URL.
107
     */
108
    private $_template;
109
    /**
110
     * @var string the regex for matching the route part. This is used in generating URL.
111
     */
112
    private $_routeRule;
113
    /**
114
     * @var array list of regex for matching parameters. This is used in generating URL.
115
     */
116
    private $_paramRules = [];
117
    /**
118
     * @var array list of parameters used in the route.
119
     */
120
    private $_routeParams = [];
121
122
123
    /**
124
     * Initializes this rule.
125
     */
126 13
    public function init()
127
    {
128 13
        if ($this->pattern === null) {
129
            throw new InvalidConfigException('UrlRule::pattern must be set.');
130
        }
131 13
        if ($this->route === null) {
132
            throw new InvalidConfigException('UrlRule::route must be set.');
133
        }
134 13
        if ($this->verb !== null) {
135 3
            if (is_array($this->verb)) {
136 3
                foreach ($this->verb as $i => $verb) {
137 3
                    $this->verb[$i] = strtoupper($verb);
138 3
                }
139 3
            } else {
140
                $this->verb = [strtoupper($this->verb)];
141
            }
142 3
        }
143 13
        if ($this->name === null) {
144 13
            $this->name = $this->pattern;
145 13
        }
146
147 13
        $this->pattern = trim($this->pattern, '/');
148 13
        $this->route = trim($this->route, '/');
149
150 13
        if ($this->host !== null) {
151 3
            $this->host = rtrim($this->host, '/');
152 3
            $this->pattern = rtrim($this->host . '/' . $this->pattern, '/');
153 13
        } elseif ($this->pattern === '') {
154 4
            $this->_template = '';
155 4
            $this->pattern = '#^$#u';
156
157 4
            return;
158 12
        } elseif (($pos = strpos($this->pattern, '://')) !== false) {
159 3
            if (($pos2 = strpos($this->pattern, '/', $pos + 3)) !== false) {
160 3
                $this->host = substr($this->pattern, 0, $pos2);
161 3
            } else {
162
                $this->host = $this->pattern;
163
            }
164 3
        } else {
165 11
            $this->pattern = '/' . $this->pattern . '/';
166
        }
167
168 12
        if (strpos($this->route, '<') !== false && preg_match_all('/<([\w._-]+)>/', $this->route, $matches)) {
169 2
            foreach ($matches[1] as $name) {
170 2
                $this->_routeParams[$name] = "<$name>";
171 2
            }
172 2
        }
173
174
        $tr = [
175 12
            '.' => '\\.',
176 12
            '*' => '\\*',
177 12
            '$' => '\\$',
178 12
            '[' => '\\[',
179 12
            ']' => '\\]',
180 12
            '(' => '\\(',
181 12
            ')' => '\\)',
182 12
        ];
183
184 12
        $tr2 = [];
185 12
        if (preg_match_all('/<([\w._-]+):?([^>]+)?>/', $this->pattern, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
186 9
            foreach ($matches as $match) {
187 9
                $name = $match[1][0];
188 9
                $pattern = isset($match[2][0]) ? $match[2][0] : '[^\/]+';
189 9
                $placeholder = 'a' . hash('crc32b', $name); // placeholder must begin with a letter
190 9
                $this->placeholders[$placeholder] = $name;
191 9
                if (array_key_exists($name, $this->defaults)) {
192 2
                    $length = strlen($match[0][0]);
193 2
                    $offset = $match[0][1];
194 2
                    if ($offset > 1 && $this->pattern[$offset - 1] === '/' && (!isset($this->pattern[$offset + $length]) || $this->pattern[$offset + $length] === '/')) {
195 2
                        $tr["/<$name>"] = "(/(?P<$placeholder>$pattern))?";
196 2
                    } else {
197 2
                        $tr["<$name>"] = "(?P<$placeholder>$pattern)?";
198
                    }
199 2
                } else {
200 9
                    $tr["<$name>"] = "(?P<$placeholder>$pattern)";
201
                }
202 9
                if (isset($this->_routeParams[$name])) {
203 2
                    $tr2["<$name>"] = "(?P<$placeholder>$pattern)";
204 2
                } else {
205 9
                    $this->_paramRules[$name] = $pattern === '[^\/]+' ? '' : "#^$pattern$#u";
206
                }
207 9
            }
208 9
        }
209
210 12
        $this->_template = preg_replace('/<([\w._-]+):?([^>]+)?>/', '<$1>', $this->pattern);
211 12
        $this->pattern = '#^' . trim(strtr($this->_template, $tr), '/') . '$#u';
212
213 12
        if (!empty($this->_routeParams)) {
214 2
            $this->_routeRule = '#^' . strtr($this->route, $tr2) . '$#u';
215 2
        }
216 12
    }
217
218
    /**
219
     * Parses the given request and returns the corresponding route and parameters.
220
     * @param UrlManager $manager the URL manager
221
     * @param Request $request the request component
222
     * @return array|boolean the parsing result. The route and the parameters are returned as an array.
223
     * If false, it means this rule cannot be used to parse this path info.
224
     */
225 6
    public function parseRequest($manager, $request)
226
    {
227 6
        if ($this->mode === self::CREATION_ONLY) {
228 1
            return false;
229
        }
230
231 6
        if (!empty($this->verb) && !in_array($request->getMethod(), $this->verb, true)) {
232 2
            return false;
233
        }
234
235 6
        $pathInfo = $request->getPathInfo();
236 6
        $suffix = (string)($this->suffix === null ? $manager->suffix : $this->suffix);
237 6
        if ($suffix !== '' && $pathInfo !== '') {
238 4
            $n = strlen($suffix);
239 4
            if (substr_compare($pathInfo, $suffix, -$n, $n) === 0) {
240 4
                $pathInfo = substr($pathInfo, 0, -$n);
241 4
                if ($pathInfo === '') {
242
                    // suffix alone is not allowed
243 1
                    return false;
244
                }
245 4
            } else {
246 3
                return false;
247
            }
248 4
        }
249
250 6
        if ($this->host !== null) {
251 1
            $pathInfo = strtolower($request->getHostInfo()) . ($pathInfo === '' ? '' : '/' . $pathInfo);
252 1
        }
253
254 6
        if (!preg_match($this->pattern, $pathInfo, $matches)) {
255 6
            return false;
256
        }
257 6
        $matches = $this->substitutePlaceholderNames($matches);
258
259 6
        foreach ($this->defaults as $name => $value) {
260 1
            if (!isset($matches[$name]) || $matches[$name] === '') {
261 1
                $matches[$name] = $value;
262 1
            }
263 6
        }
264 6
        $params = $this->defaults;
265 6
        $tr = [];
266 6
        foreach ($matches as $name => $value) {
267 6
            if (isset($this->_routeParams[$name])) {
268 1
                $tr[$this->_routeParams[$name]] = $value;
269 1
                unset($params[$name]);
270 6
            } elseif (isset($this->_paramRules[$name])) {
271 5
                $params[$name] = $value;
272 5
            }
273 6
        }
274 6
        if ($this->_routeRule !== null) {
275 1
            $route = strtr($this->route, $tr);
276 1
        } else {
277 6
            $route = $this->route;
278
        }
279
280 6
        Yii::trace("Request parsed with URL rule: {$this->name}", __METHOD__);
281
282 6
        return [$route, $params];
283
    }
284
285
    /**
286
     * Creates a URL according to the given route and parameters.
287
     * @param UrlManager $manager the URL manager
288
     * @param string $route the route. It should not have slashes at the beginning or the end.
289
     * @param array $params the parameters
290
     * @return string|boolean the created URL, or false if this rule cannot be used for creating this URL.
291
     */
292 7
    public function createUrl($manager, $route, $params)
293
    {
294 7
        if ($this->mode === self::PARSING_ONLY) {
295 2
            return false;
296
        }
297
298 7
        $tr = [];
299
300
        // match the route part first
301 7
        if ($route !== $this->route) {
302 4
            if ($this->_routeRule !== null && preg_match($this->_routeRule, $route, $matches)) {
303 1
                $matches = $this->substitutePlaceholderNames($matches);
304 1
                foreach ($this->_routeParams as $name => $token) {
305 1
                    if (isset($this->defaults[$name]) && strcmp($this->defaults[$name], $matches[$name]) === 0) {
306 1
                        $tr[$token] = '';
307 1
                    } else {
308 1
                        $tr[$token] = $matches[$name];
309
                    }
310 1
                }
311 1
            } else {
312 4
                return false;
313
            }
314 1
        }
315
316
        // match default params
317
        // if a default param is not in the route pattern, its value must also be matched
318 6
        foreach ($this->defaults as $name => $value) {
319 2
            if (isset($this->_routeParams[$name])) {
320 1
                continue;
321
            }
322 2
            if (!isset($params[$name])) {
323 1
                return false;
324 2
            } elseif (strcmp($params[$name], $value) === 0) { // strcmp will do string conversion automatically
325 2
                unset($params[$name]);
326 2
                if (isset($this->_paramRules[$name])) {
327 1
                    $tr["<$name>"] = '';
328 1
                }
329 2
            } elseif (!isset($this->_paramRules[$name])) {
330 2
                return false;
331
            }
332 6
        }
333
334
        // match params in the pattern
335 6
        foreach ($this->_paramRules as $name => $rule) {
336 3
            if (isset($params[$name]) && !is_array($params[$name]) && ($rule === '' || preg_match($rule, $params[$name]))) {
337 3
                $tr["<$name>"] = $this->encodeParams ? urlencode($params[$name]) : $params[$name];
338 3
                unset($params[$name]);
339 3
            } elseif (!isset($this->defaults[$name]) || isset($params[$name])) {
340 2
                return false;
341
            }
342 6
        }
343
344 6
        $url = trim(strtr($this->_template, $tr), '/');
345 6
        if ($this->host !== null) {
346 3
            $pos = strpos($url, '/', 8);
347 3
            if ($pos !== false) {
348 3
                $url = substr($url, 0, $pos) . preg_replace('#/+#', '/', substr($url, $pos));
349 3
            }
350 6
        } elseif (strpos($url, '//') !== false) {
351 1
            $url = preg_replace('#/+#', '/', $url);
352 1
        }
353
354 6
        if ($url !== '') {
355 5
            $url .= ($this->suffix === null ? $manager->suffix : $this->suffix);
356 5
        }
357
358 6
        if (!empty($params) && ($query = http_build_query($params)) !== '') {
359 2
            $url .= '?' . $query;
360 2
        }
361
362 6
        return $url;
363
    }
364
365
    /**
366
     * Returns list of regex for matching parameter.
367
     * @return array parameter keys and regexp rules.
368
     *
369
     * @since 2.0.6
370
     */
371
    protected function getParamRules()
372
    {
373
        return $this->_paramRules;
374
    }
375
376
    /**
377
     * Iterates over [[placeholders]] and checks whether each placeholder exists as a key in $matches array.
378
     * When found - replaces this placeholder key with a appropriate name of matching parameter.
379
     * Used in [[parseRequest()]], [[createUrl()]].
380
     *
381
     * @param array $matches result of `preg_match()` call
382
     * @return array input array with replaced placeholder keys
383
     * @see placeholders
384
     * @since 2.0.7
385
     */
386 7
    protected function substitutePlaceholderNames(array $matches)
387
    {
388 7
        foreach ($this->placeholders as $placeholder => $name) {
389 6
            if (isset($matches[$placeholder])) {
390 6
                $matches[$name] = $matches[$placeholder];
391 6
                unset($matches[$placeholder]);
392 6
            }
393 7
        }
394 7
        return $matches;
395
    }
396
}
397