Controller.php 5.32 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 27
	/**
	 * @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;

28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
	/**
	 * 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');
		}

		$args = array();
		$missing = array();
		foreach ($method->getParameters() as $param) {
			$name = $param->getName();
			if (array_key_exists($name, $params)) {
				$args[] = $params[$name];
				unset($params[$name]);
			} elseif ($param->isDefaultValueAvailable()) {
				$args[] = $param->getDefaultValue();
			} else {
				$missing[] = $name;
			}
		}

		if (!empty($missing)) {
			throw new HttpException(400, Yii::t('yii', 'Missing required parameters: {params}', array(
				'{params}' => implode(', ', $missing),
			)));
		}

		return $args;
	}

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

85 86 87 88
	/**
	 * Creates a URL using the given route and parameters.
	 *
	 * This method enhances [[UrlManager::createUrl()]] by supporting relative routes.
89
	 * A relative route is a route without a leading slash, such as "view", "post/view".
90
	 *
91 92 93 94 95 96 97
	 * - 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.
98 99 100 101 102 103 104 105
	 *
	 * @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
	 */
	public function createUrl($route, $params = array())
	{
		if (strpos($route, '/') === false) {
106
			// empty or an action ID
107
			$route = $route === '' ? $this->getRoute() : $this->getUniqueId() . '/' . $route;
108 109 110
		} elseif ($route[0] !== '/') {
			// relative to module
			$route = ltrim($this->module->getUniqueId() . '/' . $route, '/');
111 112 113
		}
		return Yii::$app->getUrlManager()->createUrl($route, $params);
	}
114 115 116 117 118

	/**
	 * Redirects the browser to the specified URL.
	 * This method is a shortcut to [[Response::redirect()]].
	 *
Qiang Xue committed
119 120 121 122 123 124 125 126 127 128
	 * @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")
	 * - an array in the format of `array($route, ...name-value pairs...)` (e.g. `array('site/index', 'ref' => 1)`)
	 *   [[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
129
	 * @param integer $statusCode the HTTP status code. If null, it will use 302.
130 131
	 * See [[http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html]]
	 * for details about HTTP status code
Qiang Xue committed
132
	 * @return Response the current response object
133 134 135
	 */
	public function redirect($url, $statusCode = null)
	{
136
		return Yii::$app->getResponse()->redirect(Html::url($url), $statusCode);
137 138
	}

Qiang Xue committed
139 140 141 142 143 144 145 146 147
	/**
	 * Redirects the browser to the home page.
	 * @return Response the current response object
	 */
	public function goHome()
	{
		return Yii::$app->getResponse()->redirect(Yii::$app->getHomeUrl());
	}

148 149 150 151 152 153 154 155 156 157 158
	/**
	 * 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
159
}