UrlRule.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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\rest;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. use yii\helpers\Inflector;
  11. use yii\web\CompositeUrlRule;
  12. /**
  13. * UrlRule is provided to simplify the creation of URL rules for RESTful API support.
  14. *
  15. * The simplest usage of UrlRule is to declare a rule like the following in the application configuration,
  16. *
  17. * ```php
  18. * [
  19. * 'class' => 'yii\rest\UrlRule',
  20. * 'controller' => 'user',
  21. * ]
  22. * ```
  23. *
  24. * The above code will create a whole set of URL rules supporting the following RESTful API endpoints:
  25. *
  26. * - `'PUT,PATCH users/<id>' => 'user/update'`: update a user
  27. * - `'DELETE users/<id>' => 'user/delete'`: delete a user
  28. * - `'GET,HEAD users/<id>' => 'user/view'`: return the details/overview/options of a user
  29. * - `'POST users' => 'user/create'`: create a new user
  30. * - `'GET,HEAD users' => 'user/index'`: return a list/overview/options of users
  31. * - `'users/<id>' => 'user/options'`: process all unhandled verbs of a user
  32. * - `'users' => 'user/options'`: process all unhandled verbs of user collection
  33. *
  34. * You may configure [[only]] and/or [[except]] to disable some of the above rules.
  35. * You may configure [[patterns]] to completely redefine your own list of rules.
  36. * You may configure [[controller]] with multiple controller IDs to generate rules for all these controllers.
  37. * For example, the following code will disable the `delete` rule and generate rules for both `user` and `post` controllers:
  38. *
  39. * ```php
  40. * [
  41. * 'class' => 'yii\rest\UrlRule',
  42. * 'controller' => ['user', 'post'],
  43. * 'except' => ['delete'],
  44. * ]
  45. * ```
  46. *
  47. * The property [[controller]] is required and should represent one or multiple controller IDs.
  48. * Each controller ID should be prefixed with the module ID if the controller is within a module.
  49. * The controller ID used in the pattern will be automatically pluralized (e.g. `user` becomes `users`
  50. * as shown in the above examples).
  51. *
  52. * For more details and usage information on UrlRule, see the [guide article on rest routing](guide:rest-routing).
  53. *
  54. * @author Qiang Xue <qiang.xue@gmail.com>
  55. * @since 2.0
  56. */
  57. class UrlRule extends CompositeUrlRule
  58. {
  59. /**
  60. * @var string the common prefix string shared by all patterns.
  61. */
  62. public $prefix;
  63. /**
  64. * @var string the suffix that will be assigned to [[\yii\web\UrlRule::suffix]] for every generated rule.
  65. */
  66. public $suffix;
  67. /**
  68. * @var string|array the controller ID (e.g. `user`, `post-comment`) that the rules in this composite rule
  69. * are dealing with. It should be prefixed with the module ID if the controller is within a module (e.g. `admin/user`).
  70. *
  71. * By default, the controller ID will be pluralized automatically when it is put in the patterns of the
  72. * generated rules. If you want to explicitly specify how the controller ID should appear in the patterns,
  73. * you may use an array with the array key being as the controller ID in the pattern, and the array value
  74. * the actual controller ID. For example, `['u' => 'user']`.
  75. *
  76. * You may also pass multiple controller IDs as an array. If this is the case, this composite rule will
  77. * generate applicable URL rules for EVERY specified controller. For example, `['user', 'post']`.
  78. */
  79. public $controller;
  80. /**
  81. * @var array list of acceptable actions. If not empty, only the actions within this array
  82. * will have the corresponding URL rules created.
  83. * @see patterns
  84. */
  85. public $only = [];
  86. /**
  87. * @var array list of actions that should be excluded. Any action found in this array
  88. * will NOT have its URL rules created.
  89. * @see patterns
  90. */
  91. public $except = [];
  92. /**
  93. * @var array patterns for supporting extra actions in addition to those listed in [[patterns]].
  94. * The keys are the patterns and the values are the corresponding action IDs.
  95. * These extra patterns will take precedence over [[patterns]].
  96. */
  97. public $extraPatterns = [];
  98. /**
  99. * @var array list of tokens that should be replaced for each pattern. The keys are the token names,
  100. * and the values are the corresponding replacements.
  101. * @see patterns
  102. */
  103. public $tokens = [
  104. '{id}' => '<id:\\d[\\d,]*>',
  105. ];
  106. /**
  107. * @var array list of possible patterns and the corresponding actions for creating the URL rules.
  108. * The keys are the patterns and the values are the corresponding actions.
  109. * The format of patterns is `Verbs Pattern`, where `Verbs` stands for a list of HTTP verbs separated
  110. * by comma (without space). If `Verbs` is not specified, it means all verbs are allowed.
  111. * `Pattern` is optional. It will be prefixed with [[prefix]]/[[controller]]/,
  112. * and tokens in it will be replaced by [[tokens]].
  113. */
  114. public $patterns = [
  115. 'PUT,PATCH {id}' => 'update',
  116. 'DELETE {id}' => 'delete',
  117. 'GET,HEAD {id}' => 'view',
  118. 'POST' => 'create',
  119. 'GET,HEAD' => 'index',
  120. '{id}' => 'options',
  121. '' => 'options',
  122. ];
  123. /**
  124. * @var array the default configuration for creating each URL rule contained by this rule.
  125. */
  126. public $ruleConfig = [
  127. 'class' => 'yii\web\UrlRule',
  128. ];
  129. /**
  130. * @var bool whether to automatically pluralize the URL names for controllers.
  131. * If true, a controller ID will appear in plural form in URLs. For example, `user` controller
  132. * will appear as `users` in URLs.
  133. * @see controller
  134. */
  135. public $pluralize = true;
  136. /**
  137. * @inheritdoc
  138. */
  139. public function init()
  140. {
  141. if (empty($this->controller)) {
  142. throw new InvalidConfigException('"controller" must be set.');
  143. }
  144. $controllers = [];
  145. foreach ((array) $this->controller as $urlName => $controller) {
  146. if (is_int($urlName)) {
  147. $urlName = $this->pluralize ? Inflector::pluralize($controller) : $controller;
  148. }
  149. $controllers[$urlName] = $controller;
  150. }
  151. $this->controller = $controllers;
  152. $this->prefix = trim($this->prefix, '/');
  153. parent::init();
  154. }
  155. /**
  156. * @inheritdoc
  157. */
  158. protected function createRules()
  159. {
  160. $only = array_flip($this->only);
  161. $except = array_flip($this->except);
  162. $patterns = $this->extraPatterns + $this->patterns;
  163. $rules = [];
  164. foreach ($this->controller as $urlName => $controller) {
  165. $prefix = trim($this->prefix . '/' . $urlName, '/');
  166. foreach ($patterns as $pattern => $action) {
  167. if (!isset($except[$action]) && (empty($only) || isset($only[$action]))) {
  168. $rules[$urlName][] = $this->createRule($pattern, $prefix, $controller . '/' . $action);
  169. }
  170. }
  171. }
  172. return $rules;
  173. }
  174. /**
  175. * Creates a URL rule using the given pattern and action.
  176. * @param string $pattern
  177. * @param string $prefix
  178. * @param string $action
  179. * @return \yii\web\UrlRuleInterface
  180. */
  181. protected function createRule($pattern, $prefix, $action)
  182. {
  183. $verbs = 'GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS';
  184. if (preg_match("/^((?:($verbs),)*($verbs))(?:\\s+(.*))?$/", $pattern, $matches)) {
  185. $verbs = explode(',', $matches[1]);
  186. $pattern = isset($matches[4]) ? $matches[4] : '';
  187. } else {
  188. $verbs = [];
  189. }
  190. $config = $this->ruleConfig;
  191. $config['verb'] = $verbs;
  192. $config['pattern'] = rtrim($prefix . '/' . strtr($pattern, $this->tokens), '/');
  193. $config['route'] = $action;
  194. if (!empty($verbs) && !in_array('GET', $verbs)) {
  195. $config['mode'] = \yii\web\UrlRule::PARSING_ONLY;
  196. }
  197. $config['suffix'] = $this->suffix;
  198. return Yii::createObject($config);
  199. }
  200. /**
  201. * @inheritdoc
  202. */
  203. public function parseRequest($manager, $request)
  204. {
  205. $pathInfo = $request->getPathInfo();
  206. foreach ($this->rules as $urlName => $rules) {
  207. if (strpos($pathInfo, $urlName) !== false) {
  208. foreach ($rules as $rule) {
  209. /* @var $rule \yii\web\UrlRule */
  210. $result = $rule->parseRequest($manager, $request);
  211. if (YII_DEBUG) {
  212. Yii::trace([
  213. 'rule' => method_exists($rule, '__toString') ? $rule->__toString() : get_class($rule),
  214. 'match' => $result !== false,
  215. 'parent' => self::className()
  216. ], __METHOD__);
  217. }
  218. if ($result !== false) {
  219. return $result;
  220. }
  221. }
  222. }
  223. }
  224. return false;
  225. }
  226. /**
  227. * @inheritdoc
  228. */
  229. public function createUrl($manager, $route, $params)
  230. {
  231. foreach ($this->controller as $urlName => $controller) {
  232. if (strpos($route, $controller) !== false) {
  233. foreach ($this->rules[$urlName] as $rule) {
  234. /* @var $rule \yii\web\UrlRule */
  235. if (($url = $rule->createUrl($manager, $route, $params)) !== false) {
  236. return $url;
  237. }
  238. }
  239. }
  240. }
  241. return false;
  242. }
  243. }