UrlManager.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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\caching\Cache;
  11. /**
  12. * UrlManager handles HTTP request parsing and creation of URLs based on a set of rules.
  13. *
  14. * UrlManager is configured as an application component in [[yii\base\Application]] by default.
  15. * You can access that instance via `Yii::$app->urlManager`.
  16. *
  17. * You can modify its configuration by adding an array to your application config under `components`
  18. * as it is shown in the following example:
  19. *
  20. * ~~~
  21. * 'urlManager' => [
  22. * 'enablePrettyUrl' => true,
  23. * 'rules' => [
  24. * // your rules go here
  25. * ],
  26. * // ...
  27. * ]
  28. * ~~~
  29. *
  30. * @property string $baseUrl The base URL that is used by [[createUrl()]] to prepend URLs it creates.
  31. * @property string $hostInfo The host info (e.g. "http://www.example.com") that is used by
  32. * [[createAbsoluteUrl()]] to prepend URLs it creates.
  33. *
  34. * @author Qiang Xue <[email protected]>
  35. * @since 2.0
  36. */
  37. class UrlManager extends Component
  38. {
  39. /**
  40. * @var boolean whether to enable pretty URLs. Instead of putting all parameters in the query
  41. * string part of a URL, pretty URLs allow using path info to represent some of the parameters
  42. * and can thus produce more user-friendly URLs, such as "/news/Yii-is-released", instead of
  43. * "/index.php?r=news/view&id=100".
  44. */
  45. public $enablePrettyUrl = false;
  46. /**
  47. * @var boolean whether to enable strict parsing. If strict parsing is enabled, the incoming
  48. * requested URL must match at least one of the [[rules]] in order to be treated as a valid request.
  49. * Otherwise, the path info part of the request will be treated as the requested route.
  50. * This property is used only when [[enablePrettyUrl]] is true.
  51. */
  52. public $enableStrictParsing = false;
  53. /**
  54. * @var array the rules for creating and parsing URLs when [[enablePrettyUrl]] is true.
  55. * This property is used only if [[enablePrettyUrl]] is true. Each element in the array
  56. * is the configuration array for creating a single URL rule. The configuration will
  57. * be merged with [[ruleConfig]] first before it is used for creating the rule object.
  58. *
  59. * A special shortcut format can be used if a rule only specifies [[UrlRule::pattern|pattern]]
  60. * and [[UrlRule::route|route]]: `'pattern' => 'route'`. That is, instead of using a configuration
  61. * array, one can use the key to represent the pattern and the value the corresponding route.
  62. * For example, `'post/<id:\d+>' => 'post/view'`.
  63. *
  64. * For RESTful routing the mentioned shortcut format also allows you to specify the
  65. * [[UrlRule::verb|HTTP verb]] that the rule should apply for.
  66. * You can do that by prepending it to the pattern, separated by space.
  67. * For example, `'PUT post/<id:\d+>' => 'post/update'`.
  68. * You may specify multiple verbs by separating them with comma
  69. * like this: `'POST,PUT post/index' => 'post/create'`.
  70. * The supported verbs in the shortcut format are: GET, HEAD, POST, PUT, PATCH and DELETE.
  71. * Note that [[UrlRule::mode|mode]] will be set to PARSING_ONLY when specifying verb in this way
  72. * so you normally would not specify a verb for normal GET request.
  73. *
  74. * Here is an example configuration for RESTful CRUD controller:
  75. *
  76. * ~~~php
  77. * [
  78. * 'dashboard' => 'site/index',
  79. *
  80. * 'POST <controller:\w+>s' => '<controller>/create',
  81. * '<controller:\w+>s' => '<controller>/index',
  82. *
  83. * 'PUT <controller:\w+>/<id:\d+>' => '<controller>/update',
  84. * 'DELETE <controller:\w+>/<id:\d+>' => '<controller>/delete',
  85. * '<controller:\w+>/<id:\d+>' => '<controller>/view',
  86. * ];
  87. * ~~~
  88. *
  89. * Note that if you modify this property after the UrlManager object is created, make sure
  90. * you populate the array with rule objects instead of rule configurations.
  91. */
  92. public $rules = [];
  93. /**
  94. * @var string the URL suffix used when in 'path' format.
  95. * For example, ".html" can be used so that the URL looks like pointing to a static HTML page.
  96. * This property is used only if [[enablePrettyUrl]] is true.
  97. */
  98. public $suffix;
  99. /**
  100. * @var boolean whether to show entry script name in the constructed URL. Defaults to true.
  101. * This property is used only if [[enablePrettyUrl]] is true.
  102. */
  103. public $showScriptName = true;
  104. /**
  105. * @var string the GET variable name for route. This property is used only if [[enablePrettyUrl]] is false.
  106. */
  107. public $routeVar = 'r';
  108. /**
  109. * @var Cache|string the cache object or the application component ID of the cache object.
  110. * Compiled URL rules will be cached through this cache object, if it is available.
  111. *
  112. * After the UrlManager object is created, if you want to change this property,
  113. * you should only assign it with a cache object.
  114. * Set this property to null if you do not want to cache the URL rules.
  115. */
  116. public $cache = 'cache';
  117. /**
  118. * @var array the default configuration of URL rules. Individual rule configurations
  119. * specified via [[rules]] will take precedence when the same property of the rule is configured.
  120. */
  121. public $ruleConfig = ['class' => 'yii\web\UrlRule'];
  122. private $_baseUrl;
  123. private $_hostInfo;
  124. /**
  125. * Initializes UrlManager.
  126. */
  127. public function init()
  128. {
  129. parent::init();
  130. $this->compileRules();
  131. }
  132. /**
  133. * Parses the URL rules.
  134. */
  135. protected function compileRules()
  136. {
  137. if (!$this->enablePrettyUrl || empty($this->rules)) {
  138. return;
  139. }
  140. if (is_string($this->cache)) {
  141. $this->cache = Yii::$app->getComponent($this->cache);
  142. }
  143. if ($this->cache instanceof Cache) {
  144. $key = __CLASS__;
  145. $hash = md5(json_encode($this->rules));
  146. if (($data = $this->cache->get($key)) !== false && isset($data[1]) && $data[1] === $hash) {
  147. $this->rules = $data[0];
  148. return;
  149. }
  150. }
  151. $rules = [];
  152. foreach ($this->rules as $key => $rule) {
  153. if (!is_array($rule)) {
  154. $rule = ['route' => $rule];
  155. if (preg_match('/^((?:(GET|HEAD|POST|PUT|PATCH|DELETE),)*(GET|HEAD|POST|PUT|PATCH|DELETE))\s+(.*)$/', $key, $matches)) {
  156. $rule['verb'] = explode(',', $matches[1]);
  157. $rule['mode'] = UrlRule::PARSING_ONLY;
  158. $key = $matches[4];
  159. }
  160. $rule['pattern'] = $key;
  161. }
  162. $rules[] = Yii::createObject(array_merge($this->ruleConfig, $rule));
  163. }
  164. $this->rules = $rules;
  165. if (isset($key, $hash)) {
  166. $this->cache->set($key, [$this->rules, $hash]);
  167. }
  168. }
  169. /**
  170. * Parses the user request.
  171. * @param Request $request the request component
  172. * @return array|boolean the route and the associated parameters. The latter is always empty
  173. * if [[enablePrettyUrl]] is false. False is returned if the current request cannot be successfully parsed.
  174. */
  175. public function parseRequest($request)
  176. {
  177. if ($this->enablePrettyUrl) {
  178. $pathInfo = $request->getPathInfo();
  179. /** @var UrlRule $rule */
  180. foreach ($this->rules as $rule) {
  181. if (($result = $rule->parseRequest($this, $request)) !== false) {
  182. Yii::trace("Request parsed with URL rule: {$rule->name}", __METHOD__);
  183. return $result;
  184. }
  185. }
  186. if ($this->enableStrictParsing) {
  187. return false;
  188. }
  189. Yii::trace('No matching URL rules. Using default URL parsing logic.', __METHOD__);
  190. $suffix = (string)$this->suffix;
  191. if ($suffix !== '' && $pathInfo !== '') {
  192. $n = strlen($this->suffix);
  193. if (substr($pathInfo, -$n) === $this->suffix) {
  194. $pathInfo = substr($pathInfo, 0, -$n);
  195. if ($pathInfo === '') {
  196. // suffix alone is not allowed
  197. return false;
  198. }
  199. } else {
  200. // suffix doesn't match
  201. return false;
  202. }
  203. }
  204. return [$pathInfo, []];
  205. } else {
  206. Yii::trace('Pretty URL not enabled. Using default URL parsing logic.', __METHOD__);
  207. $route = $request->get($this->routeVar);
  208. if (is_array($route)) {
  209. $route = '';
  210. }
  211. return [(string)$route, []];
  212. }
  213. }
  214. /**
  215. * Creates a URL using the given route and parameters.
  216. * The URL created is a relative one. Use [[createAbsoluteUrl()]] to create an absolute URL.
  217. * @param string $route the route
  218. * @param array $params the parameters (name-value pairs)
  219. * @return string the created URL
  220. */
  221. public function createUrl($route, $params = [])
  222. {
  223. $anchor = isset($params['#']) ? '#' . $params['#'] : '';
  224. unset($params['#'], $params[$this->routeVar]);
  225. $route = trim($route, '/');
  226. $baseUrl = $this->getBaseUrl();
  227. if ($this->enablePrettyUrl) {
  228. /** @var UrlRule $rule */
  229. foreach ($this->rules as $rule) {
  230. if (($url = $rule->createUrl($this, $route, $params)) !== false) {
  231. if ($rule->host !== null) {
  232. if ($baseUrl !== '' && ($pos = strpos($url, '/', 8)) !== false) {
  233. return substr($url, 0, $pos) . $baseUrl . substr($url, $pos);
  234. } else {
  235. return $url . $baseUrl . $anchor;
  236. }
  237. } else {
  238. return "$baseUrl/{$url}{$anchor}";
  239. }
  240. }
  241. }
  242. if ($this->suffix !== null) {
  243. $route .= $this->suffix;
  244. }
  245. if (!empty($params)) {
  246. $route .= '?' . http_build_query($params);
  247. }
  248. return "$baseUrl/{$route}{$anchor}";
  249. } else {
  250. $url = "$baseUrl?{$this->routeVar}=$route";
  251. if (!empty($params)) {
  252. $url .= '&' . http_build_query($params);
  253. }
  254. return $url . $anchor;
  255. }
  256. }
  257. /**
  258. * Creates an absolute URL using the given route and parameters.
  259. * This method prepends the URL created by [[createUrl()]] with the [[hostInfo]].
  260. * @param string $route the route
  261. * @param array $params the parameters (name-value pairs)
  262. * @return string the created URL
  263. * @see createUrl()
  264. */
  265. public function createAbsoluteUrl($route, $params = [])
  266. {
  267. $url = $this->createUrl($route, $params);
  268. if (strpos($url, '://') !== false) {
  269. return $url;
  270. } else {
  271. return $this->getHostInfo() . $url;
  272. }
  273. }
  274. /**
  275. * Returns the base URL that is used by [[createUrl()]] to prepend URLs it creates.
  276. * It defaults to [[Request::scriptUrl]] if [[showScriptName]] is true or [[enablePrettyUrl]] is false;
  277. * otherwise, it defaults to [[Request::baseUrl]].
  278. * @return string the base URL that is used by [[createUrl()]] to prepend URLs it creates.
  279. */
  280. public function getBaseUrl()
  281. {
  282. if ($this->_baseUrl === null) {
  283. /** @var \yii\web\Request $request */
  284. $request = Yii::$app->getRequest();
  285. $this->_baseUrl = $this->showScriptName || !$this->enablePrettyUrl ? $request->getScriptUrl() : $request->getBaseUrl();
  286. }
  287. return $this->_baseUrl;
  288. }
  289. /**
  290. * Sets the base URL that is used by [[createUrl()]] to prepend URLs it creates.
  291. * @param string $value the base URL that is used by [[createUrl()]] to prepend URLs it creates.
  292. */
  293. public function setBaseUrl($value)
  294. {
  295. $this->_baseUrl = rtrim($value, '/');
  296. }
  297. /**
  298. * Returns the host info that is used by [[createAbsoluteUrl()]] to prepend URLs it creates.
  299. * @return string the host info (e.g. "http://www.example.com") that is used by [[createAbsoluteUrl()]] to prepend URLs it creates.
  300. */
  301. public function getHostInfo()
  302. {
  303. if ($this->_hostInfo === null) {
  304. $this->_hostInfo = Yii::$app->getRequest()->getHostInfo();
  305. }
  306. return $this->_hostInfo;
  307. }
  308. /**
  309. * Sets the host info that is used by [[createAbsoluteUrl()]] to prepend URLs it creates.
  310. * @param string $value the host info (e.g. "http://www.example.com") that is used by [[createAbsoluteUrl()]] to prepend URLs it creates.
  311. */
  312. public function setHostInfo($value)
  313. {
  314. $this->_hostInfo = rtrim($value, '/');
  315. }
  316. }