UrlManager.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  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. namespace yii\web;
  8. use Yii;
  9. use yii\base\Component;
  10. use yii\base\InvalidConfigException;
  11. use yii\caching\CacheInterface;
  12. use yii\di\Instance;
  13. use yii\helpers\Url;
  14. /**
  15. * UrlManager handles HTTP request parsing and creation of URLs based on a set of rules.
  16. *
  17. * UrlManager is configured as an application component in [[\yii\base\Application]] by default.
  18. * You can access that instance via `Yii::$app->urlManager`.
  19. *
  20. * You can modify its configuration by adding an array to your application config under `components`
  21. * as it is shown in the following example:
  22. *
  23. * ```php
  24. * 'urlManager' => [
  25. * 'enablePrettyUrl' => true,
  26. * 'rules' => [
  27. * // your rules go here
  28. * ],
  29. * // ...
  30. * ]
  31. * ```
  32. *
  33. * Rules are classes implementing the [[UrlRuleInterface]], by default that is [[UrlRule]].
  34. * For nesting rules, there is also a [[GroupUrlRule]] class.
  35. *
  36. * For more details and usage information on UrlManager, see the [guide article on routing](guide:runtime-routing).
  37. *
  38. * @property string $baseUrl The base URL that is used by [[createUrl()]] to prepend to created URLs.
  39. * @property string $hostInfo The host info (e.g. `http://www.example.com`) that is used by
  40. * [[createAbsoluteUrl()]] to prepend to created URLs.
  41. * @property string $scriptUrl The entry script URL that is used by [[createUrl()]] to prepend to created
  42. * URLs.
  43. *
  44. * @author Qiang Xue <qiang.xue@gmail.com>
  45. * @since 2.0
  46. */
  47. class UrlManager extends Component
  48. {
  49. /**
  50. * @var bool whether to enable pretty URLs. Instead of putting all parameters in the query
  51. * string part of a URL, pretty URLs allow using path info to represent some of the parameters
  52. * and can thus produce more user-friendly URLs, such as "/news/Yii-is-released", instead of
  53. * "/index.php?r=news%2Fview&id=100".
  54. */
  55. public $enablePrettyUrl = false;
  56. /**
  57. * @var bool whether to enable strict parsing. If strict parsing is enabled, the incoming
  58. * requested URL must match at least one of the [[rules]] in order to be treated as a valid request.
  59. * Otherwise, the path info part of the request will be treated as the requested route.
  60. * This property is used only when [[enablePrettyUrl]] is `true`.
  61. */
  62. public $enableStrictParsing = false;
  63. /**
  64. * @var array the rules for creating and parsing URLs when [[enablePrettyUrl]] is `true`.
  65. * This property is used only if [[enablePrettyUrl]] is `true`. Each element in the array
  66. * is the configuration array for creating a single URL rule. The configuration will
  67. * be merged with [[ruleConfig]] first before it is used for creating the rule object.
  68. *
  69. * A special shortcut format can be used if a rule only specifies [[UrlRule::pattern|pattern]]
  70. * and [[UrlRule::route|route]]: `'pattern' => 'route'`. That is, instead of using a configuration
  71. * array, one can use the key to represent the pattern and the value the corresponding route.
  72. * For example, `'post/<id:\d+>' => 'post/view'`.
  73. *
  74. * For RESTful routing the mentioned shortcut format also allows you to specify the
  75. * [[UrlRule::verb|HTTP verb]] that the rule should apply for.
  76. * You can do that by prepending it to the pattern, separated by space.
  77. * For example, `'PUT post/<id:\d+>' => 'post/update'`.
  78. * You may specify multiple verbs by separating them with comma
  79. * like this: `'POST,PUT post/index' => 'post/create'`.
  80. * The supported verbs in the shortcut format are: GET, HEAD, POST, PUT, PATCH and DELETE.
  81. * Note that [[UrlRule::mode|mode]] will be set to PARSING_ONLY when specifying verb in this way
  82. * so you normally would not specify a verb for normal GET request.
  83. *
  84. * Here is an example configuration for RESTful CRUD controller:
  85. *
  86. * ```php
  87. * [
  88. * 'dashboard' => 'site/index',
  89. *
  90. * 'POST <controller:[\w-]+>' => '<controller>/create',
  91. * '<controller:[\w-]+>s' => '<controller>/index',
  92. *
  93. * 'PUT <controller:[\w-]+>/<id:\d+>' => '<controller>/update',
  94. * 'DELETE <controller:[\w-]+>/<id:\d+>' => '<controller>/delete',
  95. * '<controller:[\w-]+>/<id:\d+>' => '<controller>/view',
  96. * ];
  97. * ```
  98. *
  99. * Note that if you modify this property after the UrlManager object is created, make sure
  100. * you populate the array with rule objects instead of rule configurations.
  101. */
  102. public $rules = [];
  103. /**
  104. * @var string the URL suffix used when [[enablePrettyUrl]] is `true`.
  105. * For example, ".html" can be used so that the URL looks like pointing to a static HTML page.
  106. * This property is used only if [[enablePrettyUrl]] is `true`.
  107. */
  108. public $suffix;
  109. /**
  110. * @var bool whether to show entry script name in the constructed URL. Defaults to `true`.
  111. * This property is used only if [[enablePrettyUrl]] is `true`.
  112. */
  113. public $showScriptName = true;
  114. /**
  115. * @var string the GET parameter name for route. This property is used only if [[enablePrettyUrl]] is `false`.
  116. */
  117. public $routeParam = 'r';
  118. /**
  119. * @var CacheInterface|array|string the cache object or the application component ID of the cache object.
  120. * This can also be an array that is used to create a [[CacheInterface]] instance in case you do not want to use
  121. * an application component.
  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` or `null` if you do not want to cache the URL rules.
  127. *
  128. * Cache entries are stored for the time set by [[\yii\caching\Cache::$defaultDuration|$defaultDuration]] in
  129. * the cache configuration, which is unlimited by default. You may want to tune this value if your [[rules]]
  130. * change frequently.
  131. */
  132. public $cache = 'cache';
  133. /**
  134. * @var array the default configuration of URL rules. Individual rule configurations
  135. * specified via [[rules]] will take precedence when the same property of the rule is configured.
  136. */
  137. public $ruleConfig = ['class' => 'yii\web\UrlRule'];
  138. /**
  139. * @var UrlNormalizer|array|string|false the configuration for [[UrlNormalizer]] used by this UrlManager.
  140. * The default value is `false`, which means normalization will be skipped.
  141. * If you wish to enable URL normalization, you should configure this property manually.
  142. * For example:
  143. *
  144. * ```php
  145. * [
  146. * 'class' => 'yii\web\UrlNormalizer',
  147. * 'collapseSlashes' => true,
  148. * 'normalizeTrailingSlash' => true,
  149. * ]
  150. * ```
  151. *
  152. * @since 2.0.10
  153. */
  154. public $normalizer = false;
  155. /**
  156. * @var string the cache key for cached rules
  157. * @since 2.0.8
  158. */
  159. protected $cacheKey = __CLASS__;
  160. private $_baseUrl;
  161. private $_scriptUrl;
  162. private $_hostInfo;
  163. private $_ruleCache;
  164. /**
  165. * Initializes UrlManager.
  166. */
  167. public function init()
  168. {
  169. parent::init();
  170. if ($this->normalizer !== false) {
  171. $this->normalizer = Yii::createObject($this->normalizer);
  172. if (!$this->normalizer instanceof UrlNormalizer) {
  173. throw new InvalidConfigException('`' . get_class($this) . '::normalizer` should be an instance of `' . UrlNormalizer::className() . '` or its DI compatible configuration.');
  174. }
  175. }
  176. if (!$this->enablePrettyUrl) {
  177. return;
  178. }
  179. if ($this->cache !== false && $this->cache !== null) {
  180. try {
  181. $this->cache = Instance::ensure($this->cache, 'yii\caching\CacheInterface');
  182. } catch (InvalidConfigException $e) {
  183. Yii::warning('Unable to use cache for URL manager: ' . $e->getMessage());
  184. }
  185. }
  186. if (empty($this->rules)) {
  187. return;
  188. }
  189. $this->rules = $this->buildRules($this->rules);
  190. }
  191. /**
  192. * Adds additional URL rules.
  193. *
  194. * This method will call [[buildRules()]] to parse the given rule declarations and then append or insert
  195. * them to the existing [[rules]].
  196. *
  197. * Note that if [[enablePrettyUrl]] is `false`, this method will do nothing.
  198. *
  199. * @param array $rules the new rules to be added. Each array element represents a single rule declaration.
  200. * Please refer to [[rules]] for the acceptable rule format.
  201. * @param bool $append whether to add the new rules by appending them to the end of the existing rules.
  202. */
  203. public function addRules($rules, $append = true)
  204. {
  205. if (!$this->enablePrettyUrl) {
  206. return;
  207. }
  208. $rules = $this->buildRules($rules);
  209. if ($append) {
  210. $this->rules = array_merge($this->rules, $rules);
  211. } else {
  212. $this->rules = array_merge($rules, $this->rules);
  213. }
  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. protected function buildRules($ruleDeclarations)
  224. {
  225. $builtRules = $this->getBuiltRulesFromCache($ruleDeclarations);
  226. if ($builtRules !== false) {
  227. return $builtRules;
  228. }
  229. $builtRules = [];
  230. $verbs = 'GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS';
  231. foreach ($ruleDeclarations as $key => $rule) {
  232. if (is_string($rule)) {
  233. $rule = ['route' => $rule];
  234. if (preg_match("/^((?:($verbs),)*($verbs))\\s+(.*)$/", $key, $matches)) {
  235. $rule['verb'] = explode(',', $matches[1]);
  236. $key = $matches[4];
  237. }
  238. $rule['pattern'] = $key;
  239. }
  240. if (is_array($rule)) {
  241. $rule = Yii::createObject(array_merge($this->ruleConfig, $rule));
  242. }
  243. if (!$rule instanceof UrlRuleInterface) {
  244. throw new InvalidConfigException('URL rule class must implement UrlRuleInterface.');
  245. }
  246. $builtRules[] = $rule;
  247. }
  248. $this->setBuiltRulesCache($ruleDeclarations, $builtRules);
  249. return $builtRules;
  250. }
  251. /**
  252. * Stores $builtRules to cache, using $rulesDeclaration as a part of cache key.
  253. *
  254. * @param array $ruleDeclarations the rule declarations. Each array element represents a single rule declaration.
  255. * Please refer to [[rules]] for the acceptable rule formats.
  256. * @param UrlRuleInterface[] $builtRules the rule objects built from the given rule declarations.
  257. * @return bool whether the value is successfully stored into cache
  258. * @since 2.0.14
  259. */
  260. protected function setBuiltRulesCache($ruleDeclarations, $builtRules)
  261. {
  262. if (!$this->cache instanceof CacheInterface) {
  263. return false;
  264. }
  265. return $this->cache->set([$this->cacheKey, $this->ruleConfig, $ruleDeclarations], $builtRules);
  266. }
  267. /**
  268. * Provides the built URL rules that are associated with the $ruleDeclarations from cache.
  269. *
  270. * @param array $ruleDeclarations the rule declarations. Each array element represents a single rule declaration.
  271. * Please refer to [[rules]] for the acceptable rule formats.
  272. * @return UrlRuleInterface[]|false the rule objects built from the given rule declarations or boolean `false` when
  273. * there are no cache items for this definition exists.
  274. * @since 2.0.14
  275. */
  276. protected function getBuiltRulesFromCache($ruleDeclarations)
  277. {
  278. if (!$this->cache instanceof CacheInterface) {
  279. return false;
  280. }
  281. return $this->cache->get([$this->cacheKey, $this->ruleConfig, $ruleDeclarations]);
  282. }
  283. /**
  284. * Parses the user request.
  285. * @param Request $request the request component
  286. * @return array|bool the route and the associated parameters. The latter is always empty
  287. * if [[enablePrettyUrl]] is `false`. `false` is returned if the current request cannot be successfully parsed.
  288. */
  289. public function parseRequest($request)
  290. {
  291. if ($this->enablePrettyUrl) {
  292. /* @var $rule UrlRule */
  293. foreach ($this->rules as $rule) {
  294. $result = $rule->parseRequest($this, $request);
  295. if (YII_DEBUG) {
  296. Yii::debug([
  297. 'rule' => method_exists($rule, '__toString') ? $rule->__toString() : get_class($rule),
  298. 'match' => $result !== false,
  299. 'parent' => null,
  300. ], __METHOD__);
  301. }
  302. if ($result !== false) {
  303. return $result;
  304. }
  305. }
  306. if ($this->enableStrictParsing) {
  307. return false;
  308. }
  309. Yii::debug('No matching URL rules. Using default URL parsing logic.', __METHOD__);
  310. $suffix = (string) $this->suffix;
  311. $pathInfo = $request->getPathInfo();
  312. $normalized = false;
  313. if ($this->normalizer !== false) {
  314. $pathInfo = $this->normalizer->normalizePathInfo($pathInfo, $suffix, $normalized);
  315. }
  316. if ($suffix !== '' && $pathInfo !== '') {
  317. $n = strlen($this->suffix);
  318. if (substr_compare($pathInfo, $this->suffix, -$n, $n) === 0) {
  319. $pathInfo = substr($pathInfo, 0, -$n);
  320. if ($pathInfo === '') {
  321. // suffix alone is not allowed
  322. return false;
  323. }
  324. } else {
  325. // suffix doesn't match
  326. return false;
  327. }
  328. }
  329. if ($normalized) {
  330. // pathInfo was changed by normalizer - we need also normalize route
  331. return $this->normalizer->normalizeRoute([$pathInfo, []]);
  332. }
  333. return [$pathInfo, []];
  334. }
  335. Yii::debug('Pretty URL not enabled. Using default URL parsing logic.', __METHOD__);
  336. $route = $request->getQueryParam($this->routeParam, '');
  337. if (is_array($route)) {
  338. $route = '';
  339. }
  340. return [(string) $route, []];
  341. }
  342. /**
  343. * Creates a URL using the given route and query parameters.
  344. *
  345. * You may specify the route as a string, e.g., `site/index`. You may also use an array
  346. * if you want to specify additional query parameters for the URL being created. The
  347. * array format must be:
  348. *
  349. * ```php
  350. * // generates: /index.php?r=site%2Findex&param1=value1&param2=value2
  351. * ['site/index', 'param1' => 'value1', 'param2' => 'value2']
  352. * ```
  353. *
  354. * If you want to create a URL with an anchor, you can use the array format with a `#` parameter.
  355. * For example,
  356. *
  357. * ```php
  358. * // generates: /index.php?r=site%2Findex&param1=value1#name
  359. * ['site/index', 'param1' => 'value1', '#' => 'name']
  360. * ```
  361. *
  362. * The URL created is a relative one. Use [[createAbsoluteUrl()]] to create an absolute URL.
  363. *
  364. * Note that unlike [[\yii\helpers\Url::toRoute()]], this method always treats the given route
  365. * as an absolute route.
  366. *
  367. * @param string|array $params use a string to represent a route (e.g. `site/index`),
  368. * or an array to represent a route with query parameters (e.g. `['site/index', 'param1' => 'value1']`).
  369. * @return string the created URL
  370. */
  371. public function createUrl($params)
  372. {
  373. $params = (array) $params;
  374. $anchor = isset($params['#']) ? '#' . $params['#'] : '';
  375. unset($params['#'], $params[$this->routeParam]);
  376. $route = trim($params[0], '/');
  377. unset($params[0]);
  378. $baseUrl = $this->showScriptName || !$this->enablePrettyUrl ? $this->getScriptUrl() : $this->getBaseUrl();
  379. if ($this->enablePrettyUrl) {
  380. $cacheKey = $route . '?';
  381. foreach ($params as $key => $value) {
  382. if ($value !== null) {
  383. $cacheKey .= $key . '&';
  384. }
  385. }
  386. $url = $this->getUrlFromCache($cacheKey, $route, $params);
  387. if ($url === false) {
  388. /* @var $rule UrlRule */
  389. foreach ($this->rules as $rule) {
  390. if (in_array($rule, $this->_ruleCache[$cacheKey], true)) {
  391. // avoid redundant calls of `UrlRule::createUrl()` for rules checked in `getUrlFromCache()`
  392. // @see https://github.com/yiisoft/yii2/issues/14094
  393. continue;
  394. }
  395. $url = $rule->createUrl($this, $route, $params);
  396. if ($this->canBeCached($rule)) {
  397. $this->setRuleToCache($cacheKey, $rule);
  398. }
  399. if ($url !== false) {
  400. break;
  401. }
  402. }
  403. }
  404. if ($url !== false) {
  405. if (strpos($url, '://') !== false) {
  406. if ($baseUrl !== '' && ($pos = strpos($url, '/', 8)) !== false) {
  407. return substr($url, 0, $pos) . $baseUrl . substr($url, $pos) . $anchor;
  408. }
  409. return $url . $baseUrl . $anchor;
  410. } elseif (strncmp($url, '//', 2) === 0) {
  411. if ($baseUrl !== '' && ($pos = strpos($url, '/', 2)) !== false) {
  412. return substr($url, 0, $pos) . $baseUrl . substr($url, $pos) . $anchor;
  413. }
  414. return $url . $baseUrl . $anchor;
  415. }
  416. $url = ltrim($url, '/');
  417. return "$baseUrl/{$url}{$anchor}";
  418. }
  419. if ($this->suffix !== null) {
  420. $route .= $this->suffix;
  421. }
  422. if (!empty($params) && ($query = http_build_query($params)) !== '') {
  423. $route .= '?' . $query;
  424. }
  425. $route = ltrim($route, '/');
  426. return "$baseUrl/{$route}{$anchor}";
  427. }
  428. $url = "$baseUrl?{$this->routeParam}=" . urlencode($route);
  429. if (!empty($params) && ($query = http_build_query($params)) !== '') {
  430. $url .= '&' . $query;
  431. }
  432. return $url . $anchor;
  433. }
  434. /**
  435. * Returns the value indicating whether result of [[createUrl()]] of rule should be cached in internal cache.
  436. *
  437. * @param UrlRuleInterface $rule
  438. * @return bool `true` if result should be cached, `false` if not.
  439. * @since 2.0.12
  440. * @see getUrlFromCache()
  441. * @see setRuleToCache()
  442. * @see UrlRule::getCreateUrlStatus()
  443. */
  444. protected function canBeCached(UrlRuleInterface $rule)
  445. {
  446. return
  447. // if rule does not provide info about create status, we cache it every time to prevent bugs like #13350
  448. // @see https://github.com/yiisoft/yii2/pull/13350#discussion_r114873476
  449. !method_exists($rule, 'getCreateUrlStatus') || ($status = $rule->getCreateUrlStatus()) === null
  450. || $status === UrlRule::CREATE_STATUS_SUCCESS
  451. || $status & UrlRule::CREATE_STATUS_PARAMS_MISMATCH;
  452. }
  453. /**
  454. * Get URL from internal cache if exists.
  455. * @param string $cacheKey generated cache key to store data.
  456. * @param string $route the route (e.g. `site/index`).
  457. * @param array $params rule params.
  458. * @return bool|string the created URL
  459. * @see createUrl()
  460. * @since 2.0.8
  461. */
  462. protected function getUrlFromCache($cacheKey, $route, $params)
  463. {
  464. if (!empty($this->_ruleCache[$cacheKey])) {
  465. foreach ($this->_ruleCache[$cacheKey] as $rule) {
  466. /* @var $rule UrlRule */
  467. if (($url = $rule->createUrl($this, $route, $params)) !== false) {
  468. return $url;
  469. }
  470. }
  471. } else {
  472. $this->_ruleCache[$cacheKey] = [];
  473. }
  474. return false;
  475. }
  476. /**
  477. * Store rule (e.g. [[UrlRule]]) to internal cache.
  478. * @param $cacheKey
  479. * @param UrlRuleInterface $rule
  480. * @since 2.0.8
  481. */
  482. protected function setRuleToCache($cacheKey, UrlRuleInterface $rule)
  483. {
  484. $this->_ruleCache[$cacheKey][] = $rule;
  485. }
  486. /**
  487. * Creates an absolute URL using the given route and query parameters.
  488. *
  489. * This method prepends the URL created by [[createUrl()]] with the [[hostInfo]].
  490. *
  491. * Note that unlike [[\yii\helpers\Url::toRoute()]], this method always treats the given route
  492. * as an absolute route.
  493. *
  494. * @param string|array $params use a string to represent a route (e.g. `site/index`),
  495. * or an array to represent a route with query parameters (e.g. `['site/index', 'param1' => 'value1']`).
  496. * @param string|null $scheme the scheme to use for the URL (either `http`, `https` or empty string
  497. * for protocol-relative URL).
  498. * If not specified the scheme of the current request will be used.
  499. * @return string the created URL
  500. * @see createUrl()
  501. */
  502. public function createAbsoluteUrl($params, $scheme = null)
  503. {
  504. $params = (array) $params;
  505. $url = $this->createUrl($params);
  506. if (strpos($url, '://') === false) {
  507. $hostInfo = $this->getHostInfo();
  508. if (strncmp($url, '//', 2) === 0) {
  509. $url = substr($hostInfo, 0, strpos($hostInfo, '://')) . ':' . $url;
  510. } else {
  511. $url = $hostInfo . $url;
  512. }
  513. }
  514. return Url::ensureScheme($url, $scheme);
  515. }
  516. /**
  517. * Returns the base URL that is used by [[createUrl()]] to prepend to created URLs.
  518. * It defaults to [[Request::baseUrl]].
  519. * This is mainly used when [[enablePrettyUrl]] is `true` and [[showScriptName]] is `false`.
  520. * @return string the base URL that is used by [[createUrl()]] to prepend to created URLs.
  521. * @throws InvalidConfigException if running in console application and [[baseUrl]] is not configured.
  522. */
  523. public function getBaseUrl()
  524. {
  525. if ($this->_baseUrl === null) {
  526. $request = Yii::$app->getRequest();
  527. if ($request instanceof Request) {
  528. $this->_baseUrl = $request->getBaseUrl();
  529. } else {
  530. throw new InvalidConfigException('Please configure UrlManager::baseUrl correctly as you are running a console application.');
  531. }
  532. }
  533. return $this->_baseUrl;
  534. }
  535. /**
  536. * Sets the base URL that is used by [[createUrl()]] to prepend to created URLs.
  537. * This is mainly used when [[enablePrettyUrl]] is `true` and [[showScriptName]] is `false`.
  538. * @param string $value the base URL that is used by [[createUrl()]] to prepend to created URLs.
  539. */
  540. public function setBaseUrl($value)
  541. {
  542. $this->_baseUrl = $value === null ? null : rtrim(Yii::getAlias($value), '/');
  543. }
  544. /**
  545. * Returns the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
  546. * It defaults to [[Request::scriptUrl]].
  547. * This is mainly used when [[enablePrettyUrl]] is `false` or [[showScriptName]] is `true`.
  548. * @return string the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
  549. * @throws InvalidConfigException if running in console application and [[scriptUrl]] is not configured.
  550. */
  551. public function getScriptUrl()
  552. {
  553. if ($this->_scriptUrl === null) {
  554. $request = Yii::$app->getRequest();
  555. if ($request instanceof Request) {
  556. $this->_scriptUrl = $request->getScriptUrl();
  557. } else {
  558. throw new InvalidConfigException('Please configure UrlManager::scriptUrl correctly as you are running a console application.');
  559. }
  560. }
  561. return $this->_scriptUrl;
  562. }
  563. /**
  564. * Sets the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
  565. * This is mainly used when [[enablePrettyUrl]] is `false` or [[showScriptName]] is `true`.
  566. * @param string $value the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
  567. */
  568. public function setScriptUrl($value)
  569. {
  570. $this->_scriptUrl = $value;
  571. }
  572. /**
  573. * Returns the host info that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
  574. * @return string the host info (e.g. `http://www.example.com`) that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
  575. * @throws InvalidConfigException if running in console application and [[hostInfo]] is not configured.
  576. */
  577. public function getHostInfo()
  578. {
  579. if ($this->_hostInfo === null) {
  580. $request = Yii::$app->getRequest();
  581. if ($request instanceof \yii\web\Request) {
  582. $this->_hostInfo = $request->getHostInfo();
  583. } else {
  584. throw new InvalidConfigException('Please configure UrlManager::hostInfo correctly as you are running a console application.');
  585. }
  586. }
  587. return $this->_hostInfo;
  588. }
  589. /**
  590. * Sets the host info that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
  591. * @param string $value the host info (e.g. "http://www.example.com") that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
  592. */
  593. public function setHostInfo($value)
  594. {
  595. $this->_hostInfo = $value === null ? null : rtrim($value, '/');
  596. }
  597. }