UrlManager.php 25 KB

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