Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

253 lines
8.9KB

  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. * @author Qiang Xue <qiang.xue@gmail.com>
  53. * @since 2.0
  54. */
  55. class UrlRule extends CompositeUrlRule
  56. {
  57. /**
  58. * @var string the common prefix string shared by all patterns.
  59. */
  60. public $prefix;
  61. /**
  62. * @var string the suffix that will be assigned to [[\yii\web\UrlRule::suffix]] for every generated rule.
  63. */
  64. public $suffix;
  65. /**
  66. * @var string|array the controller ID (e.g. `user`, `post-comment`) that the rules in this composite rule
  67. * are dealing with. It should be prefixed with the module ID if the controller is within a module (e.g. `admin/user`).
  68. *
  69. * By default, the controller ID will be pluralized automatically when it is put in the patterns of the
  70. * generated rules. If you want to explicitly specify how the controller ID should appear in the patterns,
  71. * you may use an array with the array key being as the controller ID in the pattern, and the array value
  72. * the actual controller ID. For example, `['u' => 'user']`.
  73. *
  74. * You may also pass multiple controller IDs as an array. If this is the case, this composite rule will
  75. * generate applicable URL rules for EVERY specified controller. For example, `['user', 'post']`.
  76. */
  77. public $controller;
  78. /**
  79. * @var array list of acceptable actions. If not empty, only the actions within this array
  80. * will have the corresponding URL rules created.
  81. * @see patterns
  82. */
  83. public $only = [];
  84. /**
  85. * @var array list of actions that should be excluded. Any action found in this array
  86. * will NOT have its URL rules created.
  87. * @see patterns
  88. */
  89. public $except = [];
  90. /**
  91. * @var array patterns for supporting extra actions in addition to those listed in [[patterns]].
  92. * The keys are the patterns and the values are the corresponding action IDs.
  93. * These extra patterns will take precedence over [[patterns]].
  94. */
  95. public $extraPatterns = [];
  96. /**
  97. * @var array list of tokens that should be replaced for each pattern. The keys are the token names,
  98. * and the values are the corresponding replacements.
  99. * @see patterns
  100. */
  101. public $tokens = [
  102. '{id}' => '<id:\\d[\\d,]*>',
  103. ];
  104. /**
  105. * @var array list of possible patterns and the corresponding actions for creating the URL rules.
  106. * The keys are the patterns and the values are the corresponding actions.
  107. * The format of patterns is `Verbs Pattern`, where `Verbs` stands for a list of HTTP verbs separated
  108. * by comma (without space). If `Verbs` is not specified, it means all verbs are allowed.
  109. * `Pattern` is optional. It will be prefixed with [[prefix]]/[[controller]]/,
  110. * and tokens in it will be replaced by [[tokens]].
  111. */
  112. public $patterns = [
  113. 'PUT,PATCH {id}' => 'update',
  114. 'DELETE {id}' => 'delete',
  115. 'GET,HEAD {id}' => 'view',
  116. 'POST' => 'create',
  117. 'GET,HEAD' => 'index',
  118. '{id}' => 'options',
  119. '' => 'options',
  120. ];
  121. /**
  122. * @var array the default configuration for creating each URL rule contained by this rule.
  123. */
  124. public $ruleConfig = [
  125. 'class' => 'yii\web\UrlRule',
  126. ];
  127. /**
  128. * @var boolean whether to automatically pluralize the URL names for controllers.
  129. * If true, a controller ID will appear in plural form in URLs. For example, `user` controller
  130. * will appear as `users` in URLs.
  131. * @see controller
  132. */
  133. public $pluralize = true;
  134. /**
  135. * @inheritdoc
  136. */
  137. public function init()
  138. {
  139. if (empty($this->controller)) {
  140. throw new InvalidConfigException('"controller" must be set.');
  141. }
  142. $controllers = [];
  143. foreach ((array) $this->controller as $urlName => $controller) {
  144. if (is_int($urlName)) {
  145. $urlName = $this->pluralize ? Inflector::pluralize($controller) : $controller;
  146. }
  147. $controllers[$urlName] = $controller;
  148. }
  149. $this->controller = $controllers;
  150. $this->prefix = trim($this->prefix, '/');
  151. parent::init();
  152. }
  153. /**
  154. * @inheritdoc
  155. */
  156. protected function createRules()
  157. {
  158. $only = array_flip($this->only);
  159. $except = array_flip($this->except);
  160. $patterns = $this->extraPatterns + $this->patterns;
  161. $rules = [];
  162. foreach ($this->controller as $urlName => $controller) {
  163. $prefix = trim($this->prefix . '/' . $urlName, '/');
  164. foreach ($patterns as $pattern => $action) {
  165. if (!isset($except[$action]) && (empty($only) || isset($only[$action]))) {
  166. $rules[$urlName][] = $this->createRule($pattern, $prefix, $controller . '/' . $action);
  167. }
  168. }
  169. }
  170. return $rules;
  171. }
  172. /**
  173. * Creates a URL rule using the given pattern and action.
  174. * @param string $pattern
  175. * @param string $prefix
  176. * @param string $action
  177. * @return \yii\web\UrlRuleInterface
  178. */
  179. protected function createRule($pattern, $prefix, $action)
  180. {
  181. $verbs = 'GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS';
  182. if (preg_match("/^((?:($verbs),)*($verbs))(?:\\s+(.*))?$/", $pattern, $matches)) {
  183. $verbs = explode(',', $matches[1]);
  184. $pattern = isset($matches[4]) ? $matches[4] : '';
  185. } else {
  186. $verbs = [];
  187. }
  188. $config = $this->ruleConfig;
  189. $config['verb'] = $verbs;
  190. $config['pattern'] = rtrim($prefix . '/' . strtr($pattern, $this->tokens), '/');
  191. $config['route'] = $action;
  192. if (!in_array('GET', $verbs)) {
  193. $config['mode'] = \yii\web\UrlRule::PARSING_ONLY;
  194. }
  195. $config['suffix'] = $this->suffix;
  196. return Yii::createObject($config);
  197. }
  198. /**
  199. * @inheritdoc
  200. */
  201. public function parseRequest($manager, $request)
  202. {
  203. $pathInfo = $request->getPathInfo();
  204. foreach ($this->rules as $urlName => $rules) {
  205. if (strpos($pathInfo, $urlName) !== false) {
  206. foreach ($rules as $rule) {
  207. /* @var $rule \yii\web\UrlRule */
  208. if (($result = $rule->parseRequest($manager, $request)) !== false) {
  209. Yii::trace("Request parsed with URL rule: {$rule->name}", __METHOD__);
  210. return $result;
  211. }
  212. }
  213. }
  214. }
  215. return false;
  216. }
  217. /**
  218. * @inheritdoc
  219. */
  220. public function createUrl($manager, $route, $params)
  221. {
  222. foreach ($this->controller as $urlName => $controller) {
  223. if (strpos($route, $controller) !== false) {
  224. foreach ($this->rules[$urlName] as $rule) {
  225. /* @var $rule \yii\web\UrlRule */
  226. if (($url = $rule->createUrl($manager, $route, $params)) !== false) {
  227. return $url;
  228. }
  229. }
  230. }
  231. }
  232. return false;
  233. }
  234. }