Controller.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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\InlineAction;
  10. use yii\helpers\Url;
  11. /**
  12. * Controller is the base class of web controllers.
  13. *
  14. * For more details and usage information on Controller, see the [guide article on controllers](guide:structure-controllers).
  15. *
  16. * @author Qiang Xue <qiang.xue@gmail.com>
  17. * @since 2.0
  18. */
  19. class Controller extends \yii\base\Controller
  20. {
  21. /**
  22. * @var bool whether to enable CSRF validation for the actions in this controller.
  23. * CSRF validation is enabled only when both this property and [[\yii\web\Request::enableCsrfValidation]] are true.
  24. */
  25. public $enableCsrfValidation = true;
  26. /**
  27. * @var array the parameters bound to the current action.
  28. */
  29. public $actionParams = [];
  30. /**
  31. * Renders a view in response to an AJAX request.
  32. *
  33. * This method is similar to [[renderPartial()]] except that it will inject into
  34. * the rendering result with JS/CSS scripts and files which are registered with the view.
  35. * For this reason, you should use this method instead of [[renderPartial()]] to render
  36. * a view to respond to an AJAX request.
  37. *
  38. * @param string $view the view name. Please refer to [[render()]] on how to specify a view name.
  39. * @param array $params the parameters (name-value pairs) that should be made available in the view.
  40. * @return string the rendering result.
  41. */
  42. public function renderAjax($view, $params = [])
  43. {
  44. return $this->getView()->renderAjax($view, $params, $this);
  45. }
  46. /**
  47. * Send data formatted as JSON.
  48. *
  49. * This method is a shortcut for sending data formatted as JSON. It will return
  50. * the [[Application::getResponse()|response]] application component after configuring
  51. * the [[Response::$format|format]] and setting the [[Response::$data|data]] that should
  52. * be formatted. A common usage will be:
  53. *
  54. * ```php
  55. * return $this->asJson($data);
  56. * ```
  57. *
  58. * @param mixed $data the data that should be formatted.
  59. * @return Response a response that is configured to send `$data` formatted as JSON.
  60. * @since 2.0.11
  61. * @see Response::$format
  62. * @see Response::FORMAT_JSON
  63. * @see JsonResponseFormatter
  64. */
  65. public function asJson($data)
  66. {
  67. $response = Yii::$app->getResponse();
  68. $response->format = Response::FORMAT_JSON;
  69. $response->data = $data;
  70. return $response;
  71. }
  72. /**
  73. * Send data formatted as XML.
  74. *
  75. * This method is a shortcut for sending data formatted as XML. It will return
  76. * the [[Application::getResponse()|response]] application component after configuring
  77. * the [[Response::$format|format]] and setting the [[Response::$data|data]] that should
  78. * be formatted. A common usage will be:
  79. *
  80. * ```php
  81. * return $this->asXml($data);
  82. * ```
  83. *
  84. * @param mixed $data the data that should be formatted.
  85. * @return Response a response that is configured to send `$data` formatted as XML.
  86. * @since 2.0.11
  87. * @see Response::$format
  88. * @see Response::FORMAT_XML
  89. * @see XmlResponseFormatter
  90. */
  91. public function asXml($data)
  92. {
  93. $response = Yii::$app->getResponse();
  94. $response->format = Response::FORMAT_XML;
  95. $response->data = $data;
  96. return $response;
  97. }
  98. /**
  99. * Binds the parameters to the action.
  100. * This method is invoked by [[\yii\base\Action]] when it begins to run with the given parameters.
  101. * This method will check the parameter names that the action requires and return
  102. * the provided parameters according to the requirement. If there is any missing parameter,
  103. * an exception will be thrown.
  104. * @param \yii\base\Action $action the action to be bound with parameters
  105. * @param array $params the parameters to be bound to the action
  106. * @return array the valid parameters that the action can run with.
  107. * @throws BadRequestHttpException if there are missing or invalid parameters.
  108. */
  109. public function bindActionParams($action, $params)
  110. {
  111. if ($action instanceof InlineAction) {
  112. $method = new \ReflectionMethod($this, $action->actionMethod);
  113. } else {
  114. $method = new \ReflectionMethod($action, 'run');
  115. }
  116. $args = [];
  117. $missing = [];
  118. $actionParams = [];
  119. foreach ($method->getParameters() as $param) {
  120. $name = $param->getName();
  121. if (array_key_exists($name, $params)) {
  122. if ($param->isArray()) {
  123. $args[] = $actionParams[$name] = (array) $params[$name];
  124. } elseif (!is_array($params[$name])) {
  125. $args[] = $actionParams[$name] = $params[$name];
  126. } else {
  127. throw new BadRequestHttpException(Yii::t('yii', 'Invalid data received for parameter "{param}".', [
  128. 'param' => $name,
  129. ]));
  130. }
  131. unset($params[$name]);
  132. } elseif ($param->isDefaultValueAvailable()) {
  133. $args[] = $actionParams[$name] = $param->getDefaultValue();
  134. } else {
  135. $missing[] = $name;
  136. }
  137. }
  138. if (!empty($missing)) {
  139. throw new BadRequestHttpException(Yii::t('yii', 'Missing required parameters: {params}', [
  140. 'params' => implode(', ', $missing),
  141. ]));
  142. }
  143. $this->actionParams = $actionParams;
  144. return $args;
  145. }
  146. /**
  147. * {@inheritdoc}
  148. */
  149. public function beforeAction($action)
  150. {
  151. if (parent::beforeAction($action)) {
  152. if ($this->enableCsrfValidation && Yii::$app->getErrorHandler()->exception === null && !Yii::$app->getRequest()->validateCsrfToken()) {
  153. throw new BadRequestHttpException(Yii::t('yii', 'Unable to verify your data submission.'));
  154. }
  155. return true;
  156. }
  157. return false;
  158. }
  159. /**
  160. * Redirects the browser to the specified URL.
  161. * This method is a shortcut to [[Response::redirect()]].
  162. *
  163. * You can use it in an action by returning the [[Response]] directly:
  164. *
  165. * ```php
  166. * // stop executing this action and redirect to login page
  167. * return $this->redirect(['login']);
  168. * ```
  169. *
  170. * @param string|array $url the URL to be redirected to. This can be in one of the following formats:
  171. *
  172. * - a string representing a URL (e.g. "http://example.com")
  173. * - a string representing a URL alias (e.g. "@example.com")
  174. * - an array in the format of `[$route, ...name-value pairs...]` (e.g. `['site/index', 'ref' => 1]`)
  175. * [[Url::to()]] will be used to convert the array into a URL.
  176. *
  177. * Any relative URL that starts with a single forward slash "/" will be converted
  178. * into an absolute one by prepending it with the host info of the current request.
  179. *
  180. * @param int $statusCode the HTTP status code. Defaults to 302.
  181. * See <https://tools.ietf.org/html/rfc2616#section-10>
  182. * for details about HTTP status code
  183. * @return Response the current response object
  184. */
  185. public function redirect($url, $statusCode = 302)
  186. {
  187. // calling Url::to() here because Response::redirect() modifies route before calling Url::to()
  188. return Yii::$app->getResponse()->redirect(Url::to($url), $statusCode);
  189. }
  190. /**
  191. * Redirects the browser to the home page.
  192. *
  193. * You can use this method in an action by returning the [[Response]] directly:
  194. *
  195. * ```php
  196. * // stop executing this action and redirect to home page
  197. * return $this->goHome();
  198. * ```
  199. *
  200. * @return Response the current response object
  201. */
  202. public function goHome()
  203. {
  204. return Yii::$app->getResponse()->redirect(Yii::$app->getHomeUrl());
  205. }
  206. /**
  207. * Redirects the browser to the last visited page.
  208. *
  209. * You can use this method in an action by returning the [[Response]] directly:
  210. *
  211. * ```php
  212. * // stop executing this action and redirect to last visited page
  213. * return $this->goBack();
  214. * ```
  215. *
  216. * For this function to work you have to [[User::setReturnUrl()|set the return URL]] in appropriate places before.
  217. *
  218. * @param string|array $defaultUrl the default return URL in case it was not set previously.
  219. * If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to.
  220. * Please refer to [[User::setReturnUrl()]] on accepted format of the URL.
  221. * @return Response the current response object
  222. * @see User::getReturnUrl()
  223. */
  224. public function goBack($defaultUrl = null)
  225. {
  226. return Yii::$app->getResponse()->redirect(Yii::$app->getUser()->getReturnUrl($defaultUrl));
  227. }
  228. /**
  229. * Refreshes the current page.
  230. * This method is a shortcut to [[Response::refresh()]].
  231. *
  232. * You can use it in an action by returning the [[Response]] directly:
  233. *
  234. * ```php
  235. * // stop executing this action and refresh the current page
  236. * return $this->refresh();
  237. * ```
  238. *
  239. * @param string $anchor the anchor that should be appended to the redirection URL.
  240. * Defaults to empty. Make sure the anchor starts with '#' if you want to specify it.
  241. * @return Response the response object itself
  242. */
  243. public function refresh($anchor = '')
  244. {
  245. return Yii::$app->getResponse()->redirect(Yii::$app->getRequest()->getUrl() . $anchor);
  246. }
  247. }