No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

Controller.php 7.5KB

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