Controller.php 6.6 KB
Newer Older
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
Qiang Xue committed
5 6 7 8 9
 * @license http://www.yiiframework.com/license/
 */

namespace yii\web;

10
use Yii;
11
use yii\base\InlineAction;
12
use yii\helpers\Html;
13

Qiang Xue committed
14
/**
15
 * Controller is the base class of web controllers.
Qiang Xue committed
16 17 18 19 20 21
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class Controller extends \yii\base\Controller
{
22 23 24 25 26
	/**
	 * @var boolean whether to enable CSRF validation for the actions in this controller.
	 * CSRF validation is enabled only when both this property and [[Request::enableCsrfValidation]] are true.
	 */
	public $enableCsrfValidation = true;
27 28 29 30
	/**
	 * @var array the parameters bound to the current action. This is mainly used by [[getCanonicalUrl()]].
	 */
	public $actionParams = [];
31

32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
	/**
	 * Binds the parameters to the action.
	 * This method is invoked by [[Action]] when it begins to run with the given parameters.
	 * This method will check the parameter names that the action requires and return
	 * the provided parameters according to the requirement. If there is any missing parameter,
	 * an exception will be thrown.
	 * @param \yii\base\Action $action the action to be bound with parameters
	 * @param array $params the parameters to be bound to the action
	 * @return array the valid parameters that the action can run with.
	 * @throws HttpException if there are missing parameters.
	 */
	public function bindActionParams($action, $params)
	{
		if ($action instanceof InlineAction) {
			$method = new \ReflectionMethod($this, $action->actionMethod);
		} else {
			$method = new \ReflectionMethod($action, 'run');
		}

Alexander Makarov committed
51 52
		$args = [];
		$missing = [];
53
		$actionParams = [];
54 55 56
		foreach ($method->getParameters() as $param) {
			$name = $param->getName();
			if (array_key_exists($name, $params)) {
57
				$args[] = $actionParams[$name] = $params[$name];
58 59
				unset($params[$name]);
			} elseif ($param->isDefaultValueAvailable()) {
60
				$args[] = $actionParams[$name] = $param->getDefaultValue();
61 62 63 64 65 66
			} else {
				$missing[] = $name;
			}
		}

		if (!empty($missing)) {
Alexander Makarov committed
67
			throw new HttpException(400, Yii::t('yii', 'Missing required parameters: {params}', [
68
				'params' => implode(', ', $missing),
Alexander Makarov committed
69
			]));
70
		}
71 72
		
		$this->actionParams = $actionParams;
73 74 75 76

		return $args;
	}

77 78 79 80 81 82
	/**
	 * @inheritdoc
	 */
	public function beforeAction($action)
	{
		if (parent::beforeAction($action)) {
Qiang Xue committed
83 84 85 86
			if ($this->enableCsrfValidation && !Yii::$app->getRequest()->validateCsrfToken()) {
				throw new HttpException(400, Yii::t('yii', 'Unable to verify your data submission.'));
			}
			return true;
87 88 89 90 91
		} else {
			return false;
		}
	}

92 93 94 95
	/**
	 * Creates a URL using the given route and parameters.
	 *
	 * This method enhances [[UrlManager::createUrl()]] by supporting relative routes.
96
	 * A relative route is a route without a leading slash, such as "view", "post/view".
97
	 *
98 99 100 101 102 103 104
	 * - If the route is an empty string, the current [[route]] will be used;
	 * - If the route contains no slashes at all, it is considered to be an action ID
	 *   of the current controller and will be prepended with [[uniqueId]];
	 * - If the route has no leading slash, it is considered to be a route relative
	 *   to the current module and will be prepended with the module's uniqueId.
	 *
	 * After this route conversion, the method calls [[UrlManager::createUrl()]] to create a URL.
105 106 107 108 109
	 *
	 * @param string $route the route. This can be either an absolute route or a relative route.
	 * @param array $params the parameters (name-value pairs) to be included in the generated URL
	 * @return string the created URL
	 */
Alexander Makarov committed
110
	public function createUrl($route, $params = [])
111 112
	{
		if (strpos($route, '/') === false) {
113
			// empty or an action ID
114
			$route = $route === '' ? $this->getRoute() : $this->getUniqueId() . '/' . $route;
115 116 117
		} elseif ($route[0] !== '/') {
			// relative to module
			$route = ltrim($this->module->getUniqueId() . '/' . $route, '/');
118 119 120
		}
		return Yii::$app->getUrlManager()->createUrl($route, $params);
	}
121

122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
	/**
	 * Returns the canonical URL of the currently requested page.
	 * The canonical URL is constructed using [[route]] and [[actionParams]]. You may use the following code
	 * in the layout view to add a link tag about canonical URL:
	 *
	 * ~~~
	 * $this->registerLinkTag(['rel' => 'canonical', 'href' => Yii::$app->controller->canonicalUrl]);
	 * ~~~
	 *
	 * @return string
	 */
	public function getCanonicalUrl()
	{
		return Yii::$app->getUrlManager()->createAbsoluteUrl($this->getRoute(), $this->actionParams);
	}

138 139 140 141
	/**
	 * Redirects the browser to the specified URL.
	 * This method is a shortcut to [[Response::redirect()]].
	 *
Qiang Xue committed
142 143 144 145
	 * @param string|array $url the URL to be redirected to. This can be in one of the following formats:
	 *
	 * - a string representing a URL (e.g. "http://example.com")
	 * - a string representing a URL alias (e.g. "@example.com")
Alexander Makarov committed
146
	 * - an array in the format of `[$route, ...name-value pairs...]` (e.g. `['site/index', 'ref' => 1]`)
Qiang Xue committed
147 148 149 150 151
	 *   [[Html::url()]] will be used to convert the array into a URL.
	 *
	 * Any relative URL will be converted into an absolute one by prepending it with the host info
	 * of the current request.
	 *
Qiang Xue committed
152
	 * @param integer $statusCode the HTTP status code. If null, it will use 302.
153 154
	 * See [[http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html]]
	 * for details about HTTP status code
Qiang Xue committed
155
	 * @return Response the current response object
156 157 158
	 */
	public function redirect($url, $statusCode = null)
	{
159
		return Yii::$app->getResponse()->redirect(Html::url($url), $statusCode);
160 161
	}

Qiang Xue committed
162 163 164 165 166 167 168 169 170
	/**
	 * Redirects the browser to the home page.
	 * @return Response the current response object
	 */
	public function goHome()
	{
		return Yii::$app->getResponse()->redirect(Yii::$app->getHomeUrl());
	}

171 172 173 174 175 176 177 178 179 180 181 182 183
	/**
	 * Redirects the browser to the last visited page.
	 * @param string|array $defaultUrl the default return URL in case it was not set previously.
	 * If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to.
	 * Please refer to [[User::setReturnUrl()]] on accepted format of the URL.
	 * @return Response the current response object
	 * @see User::getReturnUrl()
	 */
	public function goBack($defaultUrl = null)
	{
		return Yii::$app->getResponse()->redirect(Yii::$app->getUser()->getReturnUrl($defaultUrl));
	}

184 185 186 187 188 189 190 191 192 193 194
	/**
	 * Refreshes the current page.
	 * This method is a shortcut to [[Response::refresh()]].
	 * @param string $anchor the anchor that should be appended to the redirection URL.
	 * Defaults to empty. Make sure the anchor starts with '#' if you want to specify it.
	 * @return Response the response object itself
	 */
	public function refresh($anchor = '')
	{
		return Yii::$app->getResponse()->redirect(Yii::$app->getRequest()->getUrl() . $anchor);
	}
Zander Baldwin committed
195
}