Completed
Push — master ( d39d3e...a1b5f0 )
by Dmitry
14:38
created

UrlManager::getHostInfo()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.0261

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 6
cts 7
cp 0.8571
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 3
nop 0
crap 3.0261
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\Component;
12
use yii\base\InvalidConfigException;
13
use yii\caching\CacheInterface;
14
use yii\helpers\Url;
15
16
/**
17
 * UrlManager handles HTTP request parsing and creation of URLs based on a set of rules.
18
 *
19
 * UrlManager is configured as an application component in [[\yii\base\Application]] by default.
20
 * You can access that instance via `Yii::$app->urlManager`.
21
 *
22
 * You can modify its configuration by adding an array to your application config under `components`
23
 * as it is shown in the following example:
24
 *
25
 * ```php
26
 * 'urlManager' => [
27
 *     'enablePrettyUrl' => true,
28
 *     'rules' => [
29
 *         // your rules go here
30
 *     ],
31
 *     // ...
32
 * ]
33
 * ```
34
 *
35
 * Rules are classes implementing the [[UrlRuleInterface]], by default that is [[UrlRule]].
36
 * For nesting rules, there is also a [[GroupUrlRule]] class.
37
 *
38
 * For more details and usage information on UrlManager, see the [guide article on routing](guide:runtime-routing).
39
 *
40
 * @property string $baseUrl The base URL that is used by [[createUrl()]] to prepend to created URLs.
41
 * @property string $hostInfo The host info (e.g. `http://www.example.com`) that is used by
42
 * [[createAbsoluteUrl()]] to prepend to created URLs.
43
 * @property string $scriptUrl The entry script URL that is used by [[createUrl()]] to prepend to created
44
 * URLs.
45
 *
46
 * @author Qiang Xue <[email protected]>
47
 * @since 2.0
48
 */
49
class UrlManager extends Component
50
{
51
    /**
52
     * @var bool whether to enable pretty URLs. Instead of putting all parameters in the query
53
     * string part of a URL, pretty URLs allow using path info to represent some of the parameters
54
     * and can thus produce more user-friendly URLs, such as "/news/Yii-is-released", instead of
55
     * "/index.php?r=news%2Fview&id=100".
56
     */
57
    public $enablePrettyUrl = false;
58
    /**
59
     * @var bool whether to enable strict parsing. If strict parsing is enabled, the incoming
60
     * requested URL must match at least one of the [[rules]] in order to be treated as a valid request.
61
     * Otherwise, the path info part of the request will be treated as the requested route.
62
     * This property is used only when [[enablePrettyUrl]] is `true`.
63
     */
64
    public $enableStrictParsing = false;
65
    /**
66
     * @var array the rules for creating and parsing URLs when [[enablePrettyUrl]] is `true`.
67
     * This property is used only if [[enablePrettyUrl]] is `true`. Each element in the array
68
     * is the configuration array for creating a single URL rule. The configuration will
69
     * be merged with [[ruleConfig]] first before it is used for creating the rule object.
70
     *
71
     * A special shortcut format can be used if a rule only specifies [[UrlRule::pattern|pattern]]
72
     * and [[UrlRule::route|route]]: `'pattern' => 'route'`. That is, instead of using a configuration
73
     * array, one can use the key to represent the pattern and the value the corresponding route.
74
     * For example, `'post/<id:\d+>' => 'post/view'`.
75
     *
76
     * For RESTful routing the mentioned shortcut format also allows you to specify the
77
     * [[UrlRule::verb|HTTP verb]] that the rule should apply for.
78
     * You can do that  by prepending it to the pattern, separated by space.
79
     * For example, `'PUT post/<id:\d+>' => 'post/update'`.
80
     * You may specify multiple verbs by separating them with comma
81
     * like this: `'POST,PUT post/index' => 'post/create'`.
82
     * The supported verbs in the shortcut format are: GET, HEAD, POST, PUT, PATCH and DELETE.
83
     * Note that [[UrlRule::mode|mode]] will be set to PARSING_ONLY when specifying verb in this way
84
     * so you normally would not specify a verb for normal GET request.
85
     *
86
     * Here is an example configuration for RESTful CRUD controller:
87
     *
88
     * ```php
89
     * [
90
     *     'dashboard' => 'site/index',
91
     *
92
     *     'POST <controller:[\w-]+>s' => '<controller>/create',
93
     *     '<controller:[\w-]+>s' => '<controller>/index',
94
     *
95
     *     'PUT <controller:[\w-]+>/<id:\d+>'    => '<controller>/update',
96
     *     'DELETE <controller:[\w-]+>/<id:\d+>' => '<controller>/delete',
97
     *     '<controller:[\w-]+>/<id:\d+>'        => '<controller>/view',
98
     * ];
99
     * ```
100
     *
101
     * Note that if you modify this property after the UrlManager object is created, make sure
102
     * you populate the array with rule objects instead of rule configurations.
103
     */
104
    public $rules = [];
105
    /**
106
     * @var string the URL suffix used when [[enablePrettyUrl]] is `true`.
107
     * For example, ".html" can be used so that the URL looks like pointing to a static HTML page.
108
     * This property is used only if [[enablePrettyUrl]] is `true`.
109
     */
110
    public $suffix;
111
    /**
112
     * @var bool whether to show entry script name in the constructed URL. Defaults to `true`.
113
     * This property is used only if [[enablePrettyUrl]] is `true`.
114
     */
115
    public $showScriptName = true;
116
    /**
117
     * @var string the GET parameter name for route. This property is used only if [[enablePrettyUrl]] is `false`.
118
     */
119
    public $routeParam = 'r';
120
    /**
121
     * @var CacheInterface|string the cache object or the application component ID of the cache object.
122
     * Compiled URL rules will be cached through this cache object, if it is available.
123
     *
124
     * After the UrlManager object is created, if you want to change this property,
125
     * you should only assign it with a cache object.
126
     * Set this property to `false` if you do not want to cache the URL rules.
127
     */
128
    public $cache = 'cache';
129
    /**
130
     * @var array the default configuration of URL rules. Individual rule configurations
131
     * specified via [[rules]] will take precedence when the same property of the rule is configured.
132
     */
133
    public $ruleConfig = ['class' => 'yii\web\UrlRule'];
134
    /**
135
     * @var UrlNormalizer|array|string|false the configuration for [[UrlNormalizer]] used by this UrlManager.
136
     * The default value is `false`, which means normalization will be skipped.
137
     * If you wish to enable URL normalization, you should configure this property manually.
138
     * For example:
139
     *
140
     * ```php
141
     * [
142
     *     'class' => 'yii\web\UrlNormalizer',
143
     *     'collapseSlashes' => true,
144
     *     'normalizeTrailingSlash' => true,
145
     * ]
146
     * ```
147
     *
148
     * @since 2.0.10
149
     */
150
    public $normalizer = false;
151
152
    /**
153
     * @var string the cache key for cached rules
154
     * @since 2.0.8
155
     */
156
    protected $cacheKey = __CLASS__;
157
158
    private $_baseUrl;
159
    private $_scriptUrl;
160
    private $_hostInfo;
161
    private $_ruleCache;
162
163
164
    /**
165
     * Initializes UrlManager.
166
     */
167 175
    public function init()
168
    {
169 175
        parent::init();
170
171 175
        if ($this->normalizer !== false) {
172 3
            $this->normalizer = Yii::createObject($this->normalizer);
173 3
            if (!$this->normalizer instanceof UrlNormalizer) {
174
                throw new InvalidConfigException('`' . get_class($this) . '::normalizer` should be an instance of `' . UrlNormalizer::className() . '` or its DI compatible configuration.');
0 ignored issues
show
Deprecated Code introduced by
The method yii\base\BaseObject::className() has been deprecated with message: 2.0.14 Use `::class`.

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

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

Loading history...
175
            }
176
        }
177
178 175
        if (!$this->enablePrettyUrl) {
179 78
            return;
180
        }
181 97
        if (is_string($this->cache)) {
182 1
            $this->cache = Yii::$app->get($this->cache, false);
183
        }
184 97
        if (empty($this->rules)) {
185 21
            return;
186
        }
187 77
        $this->rules = $this->buildRules($this->rules);
188 77
    }
189
190
    /**
191
     * Adds additional URL rules.
192
     *
193
     * This method will call [[buildRules()]] to parse the given rule declarations and then append or insert
194
     * them to the existing [[rules]].
195
     *
196
     * Note that if [[enablePrettyUrl]] is `false`, this method will do nothing.
197
     *
198
     * @param array $rules the new rules to be added. Each array element represents a single rule declaration.
199
     * Please refer to [[rules]] for the acceptable rule format.
200
     * @param bool $append whether to add the new rules by appending them to the end of the existing rules.
201
     */
202 3
    public function addRules($rules, $append = true)
203
    {
204 3
        if (!$this->enablePrettyUrl) {
205
            return;
206
        }
207 3
        $rules = $this->buildRules($rules);
208 3
        if ($append) {
209 2
            $this->rules = array_merge($this->rules, $rules);
210
        } else {
211 1
            $this->rules = array_merge($rules, $this->rules);
212
        }
213 3
    }
214
215
    /**
216
     * Builds URL rule objects from the given rule declarations.
217
     *
218
     * @param array $ruleDeclarations the rule declarations. Each array element represents a single rule declaration.
219
     * Please refer to [[rules]] for the acceptable rule formats.
220
     * @return UrlRuleInterface[] the rule objects built from the given rule declarations
221
     * @throws InvalidConfigException if a rule declaration is invalid
222
     */
223 77
    protected function buildRules($ruleDeclarations)
224
    {
225 77
        $builtRules = $this->getBuiltRulesFromCache($ruleDeclarations);
226 77
        if ($builtRules !== false) {
227 2
            return $builtRules;
228
        }
229
230 76
        $builtRules = [];
231 76
        $verbs = 'GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS';
232 76
        foreach ($ruleDeclarations as $key => $rule) {
233 76
            if (is_string($rule)) {
234 69
                $rule = ['route' => $rule];
235 69
                if (preg_match("/^((?:($verbs),)*($verbs))\\s+(.*)$/", $key, $matches)) {
236 1
                    $rule['verb'] = explode(',', $matches[1]);
237
                    // rules that are not applicable for GET requests should not be used to create URLs
238 1
                    if (!in_array('GET', $rule['verb'], true)) {
239 1
                        $rule['mode'] = UrlRule::PARSING_ONLY;
240
                    }
241 1
                    $key = $matches[4];
242
                }
243 69
                $rule['pattern'] = $key;
244
            }
245 76
            if (is_array($rule)) {
246 74
                $rule = Yii::createObject(array_merge($this->ruleConfig, $rule));
247
            }
248 76
            if (!$rule instanceof UrlRuleInterface) {
249
                throw new InvalidConfigException('URL rule class must implement UrlRuleInterface.');
250
            }
251 76
            $builtRules[] = $rule;
252
        }
253
254 76
        $this->cacheBuiltRules($ruleDeclarations, $builtRules);
255
256 76
        return $builtRules;
257
    }
258
259
    /**
260
     * Stores $builtRules to cache, using $rulesDeclaration as a part of cache key.
261
     *
262
     * @param array $ruleDeclarations the rule declarations. Each array element represents a single rule declaration.
263
     * Please refer to [[rules]] for the acceptable rule formats.
264
     * @param UrlRuleInterface[] $builtRules the rule objects built from the given rule declarations.
265
     * @return bool whether the value is successfully stored into cache
266
     * @since 2.0.14
267
     */
268 76
    protected function cacheBuiltRules($ruleDeclarations, $builtRules)
269
    {
270 76
        if (!$this->cache instanceof CacheInterface) {
271 74
            return false;
272
        }
273
274 2
        return $this->cache->set([$this->cacheKey, $ruleDeclarations], $builtRules);
275
    }
276
277
    /**
278
     * Provides the built URL rules that are associated with the $ruleDeclarations from cache.
279
     *
280
     * @param array $ruleDeclarations the rule declarations. Each array element represents a single rule declaration.
281
     * Please refer to [[rules]] for the acceptable rule formats.
282
     * @return UrlRuleInterface[]|false the rule objects built from the given rule declarations or boolean `false` when
283
     * there are no cache items for this definition exists.
284
     * @since 2.0.14
285
     */
286 77
    protected function getBuiltRulesFromCache($ruleDeclarations)
287
    {
288 77
        if (!$this->cache instanceof CacheInterface) {
289 74
            return false;
290
        }
291
292 3
        return $this->cache->get([$this->cacheKey, $ruleDeclarations]);
293
    }
294
295
    /**
296
     * Parses the user request.
297
     * @param Request $request the request component
298
     * @return array|bool the route and the associated parameters. The latter is always empty
299
     * if [[enablePrettyUrl]] is `false`. `false` is returned if the current request cannot be successfully parsed.
300
     */
301 16
    public function parseRequest($request)
302
    {
303 16
        if ($this->enablePrettyUrl) {
304
            /* @var $rule UrlRule */
305 13
            foreach ($this->rules as $rule) {
306 9
                $result = $rule->parseRequest($this, $request);
307 9
                if (YII_DEBUG) {
308 9
                    Yii::debug([
309 9
                        'rule' => method_exists($rule, '__toString') ? $rule->__toString() : get_class($rule),
310
                        'match' => $result !== false,
311
                        'parent' => null,
312 9
                    ], __METHOD__);
313
                }
314 9
                if ($result !== false) {
315 9
                    return $result;
316
                }
317
            }
318
319 11
            if ($this->enableStrictParsing) {
320 4
                return false;
321
            }
322
323 7
            Yii::debug('No matching URL rules. Using default URL parsing logic.', __METHOD__);
324
325 7
            $suffix = (string) $this->suffix;
326 7
            $pathInfo = $request->getPathInfo();
327 7
            $normalized = false;
328 7
            if ($this->normalizer !== false) {
329 1
                $pathInfo = $this->normalizer->normalizePathInfo($pathInfo, $suffix, $normalized);
330
            }
331 7
            if ($suffix !== '' && $pathInfo !== '') {
332 4
                $n = strlen($this->suffix);
333 4
                if (substr_compare($pathInfo, $this->suffix, -$n, $n) === 0) {
334 4
                    $pathInfo = substr($pathInfo, 0, -$n);
335 4
                    if ($pathInfo === '') {
336
                        // suffix alone is not allowed
337 4
                        return false;
338
                    }
339
                } else {
340
                    // suffix doesn't match
341 4
                    return false;
342
                }
343
            }
344
345 7
            if ($normalized) {
346
                // pathInfo was changed by normalizer - we need also normalize route
347 1
                return $this->normalizer->normalizeRoute([$pathInfo, []]);
348
            }
349
350 6
            return [$pathInfo, []];
351
        }
352
353 3
        Yii::debug('Pretty URL not enabled. Using default URL parsing logic.', __METHOD__);
354 3
        $route = $request->getQueryParam($this->routeParam, '');
355 3
        if (is_array($route)) {
356 3
            $route = '';
357
        }
358
359 3
        return [(string) $route, []];
360
    }
361
362
    /**
363
     * Creates a URL using the given route and query parameters.
364
     *
365
     * You may specify the route as a string, e.g., `site/index`. You may also use an array
366
     * if you want to specify additional query parameters for the URL being created. The
367
     * array format must be:
368
     *
369
     * ```php
370
     * // generates: /index.php?r=site%2Findex&param1=value1&param2=value2
371
     * ['site/index', 'param1' => 'value1', 'param2' => 'value2']
372
     * ```
373
     *
374
     * If you want to create a URL with an anchor, you can use the array format with a `#` parameter.
375
     * For example,
376
     *
377
     * ```php
378
     * // generates: /index.php?r=site%2Findex&param1=value1#name
379
     * ['site/index', 'param1' => 'value1', '#' => 'name']
380
     * ```
381
     *
382
     * The URL created is a relative one. Use [[createAbsoluteUrl()]] to create an absolute URL.
383
     *
384
     * Note that unlike [[\yii\helpers\Url::toRoute()]], this method always treats the given route
385
     * as an absolute route.
386
     *
387
     * @param string|array $params use a string to represent a route (e.g. `site/index`),
388
     * or an array to represent a route with query parameters (e.g. `['site/index', 'param1' => 'value1']`).
389
     * @return string the created URL
390
     */
391 130
    public function createUrl($params)
392
    {
393 130
        $params = (array) $params;
394 130
        $anchor = isset($params['#']) ? '#' . $params['#'] : '';
395 130
        unset($params['#'], $params[$this->routeParam]);
396
397 130
        $route = trim($params[0], '/');
398 130
        unset($params[0]);
399
400 130
        $baseUrl = $this->showScriptName || !$this->enablePrettyUrl ? $this->getScriptUrl() : $this->getBaseUrl();
401
402 130
        if ($this->enablePrettyUrl) {
403 80
            $cacheKey = $route . '?';
404 80
            foreach ($params as $key => $value) {
405 80
                if ($value !== null) {
406 80
                    $cacheKey .= $key . '&';
407
                }
408
            }
409
410 80
            $url = $this->getUrlFromCache($cacheKey, $route, $params);
411 80
            if ($url === false) {
412
                /* @var $rule UrlRule */
413 80
                foreach ($this->rules as $rule) {
414 64
                    if (in_array($rule, $this->_ruleCache[$cacheKey], true)) {
415
                        // avoid redundant calls of `UrlRule::createUrl()` for rules checked in `getUrlFromCache()`
416
                        // @see https://github.com/yiisoft/yii2/issues/14094
417 21
                        continue;
418
                    }
419 64
                    $url = $rule->createUrl($this, $route, $params);
420 64
                    if ($this->canBeCached($rule)) {
421 63
                        $this->setRuleToCache($cacheKey, $rule);
422
                    }
423 64
                    if ($url !== false) {
424 64
                        break;
425
                    }
426
                }
427
            }
428
429 80
            if ($url !== false) {
430 63
                if (strpos($url, '://') !== false) {
431 8
                    if ($baseUrl !== '' && ($pos = strpos($url, '/', 8)) !== false) {
432 3
                        return substr($url, 0, $pos) . $baseUrl . substr($url, $pos) . $anchor;
433
                    }
434
435 5
                    return $url . $baseUrl . $anchor;
436 55
                } elseif (strpos($url, '//') === 0) {
437 4
                    if ($baseUrl !== '' && ($pos = strpos($url, '/', 2)) !== false) {
438 3
                        return substr($url, 0, $pos) . $baseUrl . substr($url, $pos) . $anchor;
439
                    }
440
441 4
                    return $url . $baseUrl . $anchor;
442
                }
443
444 51
                $url = ltrim($url, '/');
445 51
                return "$baseUrl/{$url}{$anchor}";
446
            }
447
448 65
            if ($this->suffix !== null) {
449 24
                $route .= $this->suffix;
450
            }
451 65
            if (!empty($params) && ($query = http_build_query($params)) !== '') {
452 49
                $route .= '?' . $query;
453
            }
454
455 65
            $route = ltrim($route, '/');
456 65
            return "$baseUrl/{$route}{$anchor}";
457
        }
458
459 50
        $url = "$baseUrl?{$this->routeParam}=" . urlencode($route);
460 50
        if (!empty($params) && ($query = http_build_query($params)) !== '') {
461 40
            $url .= '&' . $query;
462
        }
463
464 50
        return $url . $anchor;
465
    }
466
467
    /**
468
     * Returns the value indicating whether result of [[createUrl()]] of rule should be cached in internal cache.
469
     *
470
     * @param UrlRuleInterface $rule
471
     * @return bool `true` if result should be cached, `false` if not.
472
     * @since 2.0.12
473
     * @see getUrlFromCache()
474
     * @see setRuleToCache()
475
     * @see UrlRule::getCreateUrlStatus()
476
     */
477 64
    protected function canBeCached(UrlRuleInterface $rule)
478
    {
479
        return
480
            // if rule does not provide info about create status, we cache it every time to prevent bugs like #13350
481
            // @see https://github.com/yiisoft/yii2/pull/13350#discussion_r114873476
482 64
            !method_exists($rule, 'getCreateUrlStatus') || ($status = $rule->getCreateUrlStatus()) === null
0 ignored issues
show
Bug introduced by
The method getCreateUrlStatus() does not exist on yii\web\UrlRuleInterface. Did you maybe mean createUrl()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
483 64
            || $status === UrlRule::CREATE_STATUS_SUCCESS
484 64
            || $status & UrlRule::CREATE_STATUS_PARAMS_MISMATCH;
485
    }
486
487
    /**
488
     * Get URL from internal cache if exists.
489
     * @param string $cacheKey generated cache key to store data.
490
     * @param string $route the route (e.g. `site/index`).
491
     * @param array $params rule params.
492
     * @return bool|string the created URL
493
     * @see createUrl()
494
     * @since 2.0.8
495
     */
496 80
    protected function getUrlFromCache($cacheKey, $route, $params)
497
    {
498 80
        if (!empty($this->_ruleCache[$cacheKey])) {
499 63
            foreach ($this->_ruleCache[$cacheKey] as $rule) {
500
                /* @var $rule UrlRule */
501 63
                if (($url = $rule->createUrl($this, $route, $params)) !== false) {
502 63
                    return $url;
503
                }
504
            }
505
        } else {
506 80
            $this->_ruleCache[$cacheKey] = [];
507
        }
508
509 80
        return false;
510
    }
511
512
    /**
513
     * Store rule (e.g. [[UrlRule]]) to internal cache.
514
     * @param $cacheKey
515
     * @param UrlRuleInterface $rule
516
     * @since 2.0.8
517
     */
518 63
    protected function setRuleToCache($cacheKey, UrlRuleInterface $rule)
519
    {
520 63
        $this->_ruleCache[$cacheKey][] = $rule;
521 63
    }
522
523
    /**
524
     * Creates an absolute URL using the given route and query parameters.
525
     *
526
     * This method prepends the URL created by [[createUrl()]] with the [[hostInfo]].
527
     *
528
     * Note that unlike [[\yii\helpers\Url::toRoute()]], this method always treats the given route
529
     * as an absolute route.
530
     *
531
     * @param string|array $params use a string to represent a route (e.g. `site/index`),
532
     * or an array to represent a route with query parameters (e.g. `['site/index', 'param1' => 'value1']`).
533
     * @param string|null $scheme the scheme to use for the URL (either `http`, `https` or empty string
534
     * for protocol-relative URL).
535
     * If not specified the scheme of the current request will be used.
536
     * @return string the created URL
537
     * @see createUrl()
538
     */
539 58
    public function createAbsoluteUrl($params, $scheme = null)
540
    {
541 58
        $params = (array) $params;
542 58
        $url = $this->createUrl($params);
543 58
        if (strpos($url, '://') === false) {
544 54
            $hostInfo = $this->getHostInfo();
545 54
            if (strpos($url, '//') === 0) {
546 4
                $url = substr($hostInfo, 0, strpos($hostInfo, '://')) . ':' . $url;
547
            } else {
548 54
                $url = $hostInfo . $url;
549
            }
550
        }
551
552 58
        return Url::ensureScheme($url, $scheme);
553
    }
554
555
    /**
556
     * Returns the base URL that is used by [[createUrl()]] to prepend to created URLs.
557
     * It defaults to [[Request::baseUrl]].
558
     * This is mainly used when [[enablePrettyUrl]] is `true` and [[showScriptName]] is `false`.
559
     * @return string the base URL that is used by [[createUrl()]] to prepend to created URLs.
560
     * @throws InvalidConfigException if running in console application and [[baseUrl]] is not configured.
561
     */
562 42
    public function getBaseUrl()
563
    {
564 42
        if ($this->_baseUrl === null) {
565 1
            $request = Yii::$app->getRequest();
566 1
            if ($request instanceof Request) {
567 1
                $this->_baseUrl = $request->getBaseUrl();
568
            } else {
569
                throw new InvalidConfigException('Please configure UrlManager::baseUrl correctly as you are running a console application.');
570
            }
571
        }
572
573 42
        return $this->_baseUrl;
574
    }
575
576
    /**
577
     * Sets the base URL that is used by [[createUrl()]] to prepend to created URLs.
578
     * This is mainly used when [[enablePrettyUrl]] is `true` and [[showScriptName]] is `false`.
579
     * @param string $value the base URL that is used by [[createUrl()]] to prepend to created URLs.
580
     */
581 113
    public function setBaseUrl($value)
582
    {
583 113
        $this->_baseUrl = $value === null ? null : rtrim(Yii::getAlias($value), '/');
584 113
    }
585
586
    /**
587
     * Returns the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
588
     * It defaults to [[Request::scriptUrl]].
589
     * This is mainly used when [[enablePrettyUrl]] is `false` or [[showScriptName]] is `true`.
590
     * @return string the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
591
     * @throws InvalidConfigException if running in console application and [[scriptUrl]] is not configured.
592
     */
593 90
    public function getScriptUrl()
594
    {
595 90
        if ($this->_scriptUrl === null) {
596 12
            $request = Yii::$app->getRequest();
597 12
            if ($request instanceof Request) {
598 12
                $this->_scriptUrl = $request->getScriptUrl();
599
            } else {
600
                throw new InvalidConfigException('Please configure UrlManager::scriptUrl correctly as you are running a console application.');
601
            }
602
        }
603
604 90
        return $this->_scriptUrl;
605
    }
606
607
    /**
608
     * Sets the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
609
     * This is mainly used when [[enablePrettyUrl]] is `false` or [[showScriptName]] is `true`.
610
     * @param string $value the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
611
     */
612 125
    public function setScriptUrl($value)
613
    {
614 125
        $this->_scriptUrl = $value;
615 125
    }
616
617
    /**
618
     * Returns the host info that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
619
     * @return string the host info (e.g. `http://www.example.com`) that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
620
     * @throws InvalidConfigException if running in console application and [[hostInfo]] is not configured.
621
     */
622 56
    public function getHostInfo()
623
    {
624 56
        if ($this->_hostInfo === null) {
625 7
            $request = Yii::$app->getRequest();
626 7
            if ($request instanceof \yii\web\Request) {
627 7
                $this->_hostInfo = $request->getHostInfo();
628
            } else {
629
                throw new InvalidConfigException('Please configure UrlManager::hostInfo correctly as you are running a console application.');
630
            }
631
        }
632
633 56
        return $this->_hostInfo;
634
    }
635
636
    /**
637
     * Sets the host info that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
638
     * @param string $value the host info (e.g. "http://www.example.com") that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
639
     */
640 110
    public function setHostInfo($value)
641
    {
642 110
        $this->_hostInfo = $value === null ? null : rtrim($value, '/');
643 110
    }
644
}
645