UrlManager.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  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. // rules that are not applicable for GET requests should not be used to create URLs
  237. if (!in_array('GET', $rule['verb'], true)) {
  238. $rule['mode'] = UrlRule::PARSING_ONLY;
  239. }
  240. $key = $matches[4];
  241. }
  242. $rule['pattern'] = $key;
  243. }
  244. if (is_array($rule)) {
  245. $rule = Yii::createObject(array_merge($this->ruleConfig, $rule));
  246. }
  247. if (!$rule instanceof UrlRuleInterface) {
  248. throw new InvalidConfigException('URL rule class must implement UrlRuleInterface.');
  249. }
  250. $builtRules[] = $rule;
  251. }
  252. $this->setBuiltRulesCache($ruleDeclarations, $builtRules);
  253. return $builtRules;
  254. }
  255. /**
  256. * Stores $builtRules to cache, using $rulesDeclaration as a part of cache key.
  257. *
  258. * @param array $ruleDeclarations the rule declarations. Each array element represents a single rule declaration.
  259. * Please refer to [[rules]] for the acceptable rule formats.
  260. * @param UrlRuleInterface[] $builtRules the rule objects built from the given rule declarations.
  261. * @return bool whether the value is successfully stored into cache
  262. * @since 2.0.14
  263. */
  264. protected function setBuiltRulesCache($ruleDeclarations, $builtRules)
  265. {
  266. if (!$this->cache instanceof CacheInterface) {
  267. return false;
  268. }
  269. return $this->cache->set([$this->cacheKey, $this->ruleConfig, $ruleDeclarations], $builtRules);
  270. }
  271. /**
  272. * Provides the built URL rules that are associated with the $ruleDeclarations from cache.
  273. *
  274. * @param array $ruleDeclarations the rule declarations. Each array element represents a single rule declaration.
  275. * Please refer to [[rules]] for the acceptable rule formats.
  276. * @return UrlRuleInterface[]|false the rule objects built from the given rule declarations or boolean `false` when
  277. * there are no cache items for this definition exists.
  278. * @since 2.0.14
  279. */
  280. protected function getBuiltRulesFromCache($ruleDeclarations)
  281. {
  282. if (!$this->cache instanceof CacheInterface) {
  283. return false;
  284. }
  285. return $this->cache->get([$this->cacheKey, $this->ruleConfig, $ruleDeclarations]);
  286. }
  287. /**
  288. * Parses the user request.
  289. * @param Request $request the request component
  290. * @return array|bool the route and the associated parameters. The latter is always empty
  291. * if [[enablePrettyUrl]] is `false`. `false` is returned if the current request cannot be successfully parsed.
  292. */
  293. public function parseRequest($request)
  294. {
  295. if ($this->enablePrettyUrl) {
  296. /* @var $rule UrlRule */
  297. foreach ($this->rules as $rule) {
  298. $result = $rule->parseRequest($this, $request);
  299. if (YII_DEBUG) {
  300. Yii::debug([
  301. 'rule' => method_exists($rule, '__toString') ? $rule->__toString() : get_class($rule),
  302. 'match' => $result !== false,
  303. 'parent' => null,
  304. ], __METHOD__);
  305. }
  306. if ($result !== false) {
  307. return $result;
  308. }
  309. }
  310. if ($this->enableStrictParsing) {
  311. return false;
  312. }
  313. Yii::debug('No matching URL rules. Using default URL parsing logic.', __METHOD__);
  314. $suffix = (string) $this->suffix;
  315. $pathInfo = $request->getPathInfo();
  316. $normalized = false;
  317. if ($this->normalizer !== false) {
  318. $pathInfo = $this->normalizer->normalizePathInfo($pathInfo, $suffix, $normalized);
  319. }
  320. if ($suffix !== '' && $pathInfo !== '') {
  321. $n = strlen($this->suffix);
  322. if (substr_compare($pathInfo, $this->suffix, -$n, $n) === 0) {
  323. $pathInfo = substr($pathInfo, 0, -$n);
  324. if ($pathInfo === '') {
  325. // suffix alone is not allowed
  326. return false;
  327. }
  328. } else {
  329. // suffix doesn't match
  330. return false;
  331. }
  332. }
  333. if ($normalized) {
  334. // pathInfo was changed by normalizer - we need also normalize route
  335. return $this->normalizer->normalizeRoute([$pathInfo, []]);
  336. }
  337. return [$pathInfo, []];
  338. }
  339. Yii::debug('Pretty URL not enabled. Using default URL parsing logic.', __METHOD__);
  340. $route = $request->getQueryParam($this->routeParam, '');
  341. if (is_array($route)) {
  342. $route = '';
  343. }
  344. return [(string) $route, []];
  345. }
  346. /**
  347. * Creates a URL using the given route and query parameters.
  348. *
  349. * You may specify the route as a string, e.g., `site/index`. You may also use an array
  350. * if you want to specify additional query parameters for the URL being created. The
  351. * array format must be:
  352. *
  353. * ```php
  354. * // generates: /index.php?r=site%2Findex&param1=value1&param2=value2
  355. * ['site/index', 'param1' => 'value1', 'param2' => 'value2']
  356. * ```
  357. *
  358. * If you want to create a URL with an anchor, you can use the array format with a `#` parameter.
  359. * For example,
  360. *
  361. * ```php
  362. * // generates: /index.php?r=site%2Findex&param1=value1#name
  363. * ['site/index', 'param1' => 'value1', '#' => 'name']
  364. * ```
  365. *
  366. * The URL created is a relative one. Use [[createAbsoluteUrl()]] to create an absolute URL.
  367. *
  368. * Note that unlike [[\yii\helpers\Url::toRoute()]], this method always treats the given route
  369. * as an absolute route.
  370. *
  371. * @param string|array $params use a string to represent a route (e.g. `site/index`),
  372. * or an array to represent a route with query parameters (e.g. `['site/index', 'param1' => 'value1']`).
  373. * @return string the created URL
  374. */
  375. public function createUrl($params)
  376. {
  377. $params = (array) $params;
  378. $anchor = isset($params['#']) ? '#' . $params['#'] : '';
  379. unset($params['#'], $params[$this->routeParam]);
  380. $route = trim($params[0], '/');
  381. unset($params[0]);
  382. $baseUrl = $this->showScriptName || !$this->enablePrettyUrl ? $this->getScriptUrl() : $this->getBaseUrl();
  383. if ($this->enablePrettyUrl) {
  384. $cacheKey = $route . '?';
  385. foreach ($params as $key => $value) {
  386. if ($value !== null) {
  387. $cacheKey .= $key . '&';
  388. }
  389. }
  390. $url = $this->getUrlFromCache($cacheKey, $route, $params);
  391. if ($url === false) {
  392. /* @var $rule UrlRule */
  393. foreach ($this->rules as $rule) {
  394. if (in_array($rule, $this->_ruleCache[$cacheKey], true)) {
  395. // avoid redundant calls of `UrlRule::createUrl()` for rules checked in `getUrlFromCache()`
  396. // @see https://github.com/yiisoft/yii2/issues/14094
  397. continue;
  398. }
  399. $url = $rule->createUrl($this, $route, $params);
  400. if ($this->canBeCached($rule)) {
  401. $this->setRuleToCache($cacheKey, $rule);
  402. }
  403. if ($url !== false) {
  404. break;
  405. }
  406. }
  407. }
  408. if ($url !== false) {
  409. if (strpos($url, '://') !== false) {
  410. if ($baseUrl !== '' && ($pos = strpos($url, '/', 8)) !== false) {
  411. return substr($url, 0, $pos) . $baseUrl . substr($url, $pos) . $anchor;
  412. }
  413. return $url . $baseUrl . $anchor;
  414. } elseif (strncmp($url, '//', 2) === 0) {
  415. if ($baseUrl !== '' && ($pos = strpos($url, '/', 2)) !== false) {
  416. return substr($url, 0, $pos) . $baseUrl . substr($url, $pos) . $anchor;
  417. }
  418. return $url . $baseUrl . $anchor;
  419. }
  420. $url = ltrim($url, '/');
  421. return "$baseUrl/{$url}{$anchor}";
  422. }
  423. if ($this->suffix !== null) {
  424. $route .= $this->suffix;
  425. }
  426. if (!empty($params) && ($query = http_build_query($params)) !== '') {
  427. $route .= '?' . $query;
  428. }
  429. $route = ltrim($route, '/');
  430. return "$baseUrl/{$route}{$anchor}";
  431. }
  432. $url = "$baseUrl?{$this->routeParam}=" . urlencode($route);
  433. if (!empty($params) && ($query = http_build_query($params)) !== '') {
  434. $url .= '&' . $query;
  435. }
  436. return $url . $anchor;
  437. }
  438. /**
  439. * Returns the value indicating whether result of [[createUrl()]] of rule should be cached in internal cache.
  440. *
  441. * @param UrlRuleInterface $rule
  442. * @return bool `true` if result should be cached, `false` if not.
  443. * @since 2.0.12
  444. * @see getUrlFromCache()
  445. * @see setRuleToCache()
  446. * @see UrlRule::getCreateUrlStatus()
  447. */
  448. protected function canBeCached(UrlRuleInterface $rule)
  449. {
  450. return
  451. // if rule does not provide info about create status, we cache it every time to prevent bugs like #13350
  452. // @see https://github.com/yiisoft/yii2/pull/13350#discussion_r114873476
  453. !method_exists($rule, 'getCreateUrlStatus') || ($status = $rule->getCreateUrlStatus()) === null
  454. || $status === UrlRule::CREATE_STATUS_SUCCESS
  455. || $status & UrlRule::CREATE_STATUS_PARAMS_MISMATCH;
  456. }
  457. /**
  458. * Get URL from internal cache if exists.
  459. * @param string $cacheKey generated cache key to store data.
  460. * @param string $route the route (e.g. `site/index`).
  461. * @param array $params rule params.
  462. * @return bool|string the created URL
  463. * @see createUrl()
  464. * @since 2.0.8
  465. */
  466. protected function getUrlFromCache($cacheKey, $route, $params)
  467. {
  468. if (!empty($this->_ruleCache[$cacheKey])) {
  469. foreach ($this->_ruleCache[$cacheKey] as $rule) {
  470. /* @var $rule UrlRule */
  471. if (($url = $rule->createUrl($this, $route, $params)) !== false) {
  472. return $url;
  473. }
  474. }
  475. } else {
  476. $this->_ruleCache[$cacheKey] = [];
  477. }
  478. return false;
  479. }
  480. /**
  481. * Store rule (e.g. [[UrlRule]]) to internal cache.
  482. * @param $cacheKey
  483. * @param UrlRuleInterface $rule
  484. * @since 2.0.8
  485. */
  486. protected function setRuleToCache($cacheKey, UrlRuleInterface $rule)
  487. {
  488. $this->_ruleCache[$cacheKey][] = $rule;
  489. }
  490. /**
  491. * Creates an absolute URL using the given route and query parameters.
  492. *
  493. * This method prepends the URL created by [[createUrl()]] with the [[hostInfo]].
  494. *
  495. * Note that unlike [[\yii\helpers\Url::toRoute()]], this method always treats the given route
  496. * as an absolute route.
  497. *
  498. * @param string|array $params use a string to represent a route (e.g. `site/index`),
  499. * or an array to represent a route with query parameters (e.g. `['site/index', 'param1' => 'value1']`).
  500. * @param string|null $scheme the scheme to use for the URL (either `http`, `https` or empty string
  501. * for protocol-relative URL).
  502. * If not specified the scheme of the current request will be used.
  503. * @return string the created URL
  504. * @see createUrl()
  505. */
  506. public function createAbsoluteUrl($params, $scheme = null)
  507. {
  508. $params = (array) $params;
  509. $url = $this->createUrl($params);
  510. if (strpos($url, '://') === false) {
  511. $hostInfo = $this->getHostInfo();
  512. if (strncmp($url, '//', 2) === 0) {
  513. $url = substr($hostInfo, 0, strpos($hostInfo, '://')) . ':' . $url;
  514. } else {
  515. $url = $hostInfo . $url;
  516. }
  517. }
  518. return Url::ensureScheme($url, $scheme);
  519. }
  520. /**
  521. * Returns the base URL that is used by [[createUrl()]] to prepend to created URLs.
  522. * It defaults to [[Request::baseUrl]].
  523. * This is mainly used when [[enablePrettyUrl]] is `true` and [[showScriptName]] is `false`.
  524. * @return string the base URL that is used by [[createUrl()]] to prepend to created URLs.
  525. * @throws InvalidConfigException if running in console application and [[baseUrl]] is not configured.
  526. */
  527. public function getBaseUrl()
  528. {
  529. if ($this->_baseUrl === null) {
  530. $request = Yii::$app->getRequest();
  531. if ($request instanceof Request) {
  532. $this->_baseUrl = $request->getBaseUrl();
  533. } else {
  534. throw new InvalidConfigException('Please configure UrlManager::baseUrl correctly as you are running a console application.');
  535. }
  536. }
  537. return $this->_baseUrl;
  538. }
  539. /**
  540. * Sets the base URL that is used by [[createUrl()]] to prepend to created URLs.
  541. * This is mainly used when [[enablePrettyUrl]] is `true` and [[showScriptName]] is `false`.
  542. * @param string $value the base URL that is used by [[createUrl()]] to prepend to created URLs.
  543. */
  544. public function setBaseUrl($value)
  545. {
  546. $this->_baseUrl = $value === null ? null : rtrim(Yii::getAlias($value), '/');
  547. }
  548. /**
  549. * Returns the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
  550. * It defaults to [[Request::scriptUrl]].
  551. * This is mainly used when [[enablePrettyUrl]] is `false` or [[showScriptName]] is `true`.
  552. * @return string the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
  553. * @throws InvalidConfigException if running in console application and [[scriptUrl]] is not configured.
  554. */
  555. public function getScriptUrl()
  556. {
  557. if ($this->_scriptUrl === null) {
  558. $request = Yii::$app->getRequest();
  559. if ($request instanceof Request) {
  560. $this->_scriptUrl = $request->getScriptUrl();
  561. } else {
  562. throw new InvalidConfigException('Please configure UrlManager::scriptUrl correctly as you are running a console application.');
  563. }
  564. }
  565. return $this->_scriptUrl;
  566. }
  567. /**
  568. * Sets the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
  569. * This is mainly used when [[enablePrettyUrl]] is `false` or [[showScriptName]] is `true`.
  570. * @param string $value the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
  571. */
  572. public function setScriptUrl($value)
  573. {
  574. $this->_scriptUrl = $value;
  575. }
  576. /**
  577. * Returns the host info that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
  578. * @return string the host info (e.g. `http://www.example.com`) that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
  579. * @throws InvalidConfigException if running in console application and [[hostInfo]] is not configured.
  580. */
  581. public function getHostInfo()
  582. {
  583. if ($this->_hostInfo === null) {
  584. $request = Yii::$app->getRequest();
  585. if ($request instanceof \yii\web\Request) {
  586. $this->_hostInfo = $request->getHostInfo();
  587. } else {
  588. throw new InvalidConfigException('Please configure UrlManager::hostInfo correctly as you are running a console application.');
  589. }
  590. }
  591. return $this->_hostInfo;
  592. }
  593. /**
  594. * Sets the host info that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
  595. * @param string $value the host info (e.g. "http://www.example.com") that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
  596. */
  597. public function setHostInfo($value)
  598. {
  599. $this->_hostInfo = $value === null ? null : rtrim($value, '/');
  600. }
  601. }