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

namespace yii\console;

Qiang Xue committed
10
use Yii;
Qiang Xue committed
11
use yii\base\Action;
Qiang Xue committed
12
use yii\base\InlineAction;
Qiang Xue committed
13
use yii\base\InvalidRouteException;
14
use yii\helpers\Console;
Qiang Xue committed
15

Alexander Makarov committed
16
/**
Qiang Xue committed
17
 * Controller is the base class of console command classes.
Alexander Makarov committed
18
 *
Qiang Xue committed
19 20
 * A controller consists of one or several actions known as sub-commands.
 * Users call a console command by specifying the corresponding route which identifies a controller action.
21
 * The `yii` program is used when calling a console command, like the following:
Alexander Makarov committed
22
 *
Qiang Xue committed
23
 * ~~~
24
 * yii <route> [--param1=value1 --param2 ...]
Qiang Xue committed
25
 * ~~~
Alexander Makarov committed
26 27 28 29
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
Qiang Xue committed
30
class Controller extends \yii\base\Controller
Alexander Makarov committed
31
{
Qiang Xue committed
32
	/**
33
	 * @var boolean whether to run the command interactively.
Qiang Xue committed
34 35 36
	 */
	public $interactive = true;

37
	/**
38 39 40 41 42 43 44 45
	 * @var boolean whether to enable ANSI style in output.
	 * Defaults to null meaning auto-detect.
	 */
	private $_colors;

	/**
	 * Whether to enable ANSI style in output.
	 *
46 47 48
	 * Setting this will affect [[ansiFormat()]], [[stdout()]] and [[stderr()]].
	 * If not set it will be auto detected using [[yii\helpers\Console::streamSupportsAnsiColors()]] with STDOUT
	 * for [[ansiFormat()]] and [[stdout()]] and STDERR for [[stderr()]].
49 50 51 52 53 54 55 56 57 58 59 60 61
	 * @param resource $stream
	 * @return boolean Whether to enable ANSI style in output.
	 */
	public function getColors($stream = STDOUT)
	{
		if ($this->_colors === null) {
			return Console::streamSupportsAnsiColors($stream);
		}
		return $this->_colors;
	}

	/**
	 * Whether to enable ANSI style in output.
62
	 */
63 64 65 66
	public function setColors($value)
	{
		$this->_colors = (bool) $value;
	}
67

Qiang Xue committed
68 69 70 71 72 73 74 75 76 77 78
	/**
	 * Runs an action with the specified action ID and parameters.
	 * If the action ID is empty, the method will use [[defaultAction]].
	 * @param string $id the ID of the action to be executed.
	 * @param array $params the parameters (name-value pairs) to be passed to the action.
	 * @return integer the status of the action execution. 0 means normal, other values mean abnormal.
	 * @throws InvalidRouteException if the requested action ID cannot be resolved into an action successfully.
	 * @see createAction
	 */
	public function runAction($id, $params = array())
	{
79
		if (!empty($params)) {
Qiang Xue committed
80
			$options = $this->globalOptions();
Qiang Xue committed
81
			foreach ($params as $name => $value) {
Qiang Xue committed
82 83 84
				if (in_array($name, $options, true)) {
					$this->$name = $value;
					unset($params[$name]);
Qiang Xue committed
85 86 87 88 89 90
				}
			}
		}
		return parent::runAction($id, $params);
	}

Qiang Xue committed
91
	/**
Qiang Xue committed
92 93 94 95 96 97 98 99
	 * Binds the parameters to the action.
	 * This method is invoked by [[Action]] when it begins to run with the given parameters.
	 * This method will first bind the parameters with the [[globalOptions()|global options]]
	 * available to the action. It then validates the given arguments.
	 * @param 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 Exception if there are unknown options or missing arguments
Qiang Xue committed
100
	 */
Qiang Xue committed
101
	public function bindActionParams($action, $params)
Qiang Xue committed
102
	{
103
		if (!empty($params)) {
Qiang Xue committed
104 105 106 107 108 109 110 111
			$options = $this->globalOptions();
			foreach ($params as $name => $value) {
				if (in_array($name, $options, true)) {
					$this->$name = $value;
					unset($params[$name]);
				}
			}
		}
Qiang Xue committed
112

Qiang Xue committed
113 114
		$args = isset($params[Request::ANONYMOUS_PARAMS]) ? $params[Request::ANONYMOUS_PARAMS] : array();
		unset($params[Request::ANONYMOUS_PARAMS]);
115
		if (!empty($params)) {
116
			throw new Exception(Yii::t('yii', 'Unknown options: {params}', array(
Qiang Xue committed
117
				'{params}' => implode(', ', array_keys($params)),
Qiang Xue committed
118
			)));
Qiang Xue committed
119
		}
Qiang Xue committed
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138

		if ($action instanceof InlineAction) {
			$method = new \ReflectionMethod($this, $action->actionMethod);
		} else {
			$method = new \ReflectionMethod($action, 'run');
		}

		$missing = array();
		foreach ($method->getParameters() as $i => $param) {
			$name = $param->getName();
			if (!isset($args[$i])) {
				if ($param->isDefaultValueAvailable()) {
					$args[$i] = $param->getDefaultValue();
				} else {
					$missing[] = $name;
				}
			}
		}

139
		if (!empty($missing)) {
140
			throw new Exception(Yii::t('yii', 'Missing required arguments: {params}', array(
Qiang Xue committed
141
				'{params}' => implode(', ', $missing),
Qiang Xue committed
142
			)));
Alexander Makarov committed
143
		}
Qiang Xue committed
144 145

		return $args;
Alexander Makarov committed
146
	}
Alexander Makarov committed
147

148 149 150 151 152 153 154
	/**
	 * Formats a string with ANSI codes
	 *
	 * You may pass additional parameters using the constants defined in [[yii\helpers\base\Console]].
	 *
	 * Example:
	 * ~~~
155
	 * $this->ansiFormat('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
156 157 158 159 160
	 * ~~~
	 *
	 * @param string $string the string to be formatted
	 * @return string
	 */
161
	public function ansiFormat($string)
162
	{
163
		if ($this->getColors()) {
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
			$args = func_get_args();
			array_shift($args);
			$string = Console::ansiFormat($string, $args);
		}
		return $string;
	}

	/**
	 * Prints a string to STDOUT
	 *
	 * You may optionally format the string with ANSI codes by
	 * passing additional parameters using the constants defined in [[yii\helpers\base\Console]].
	 *
	 * Example:
	 * ~~~
	 * $this->stdout('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
	 * ~~~
	 *
	 * @param string $string the string to print
	 * @return int|boolean Number of bytes printed or false on error
	 */
	public function stdout($string)
	{
187
		if ($this->getColors()) {
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
			$args = func_get_args();
			array_shift($args);
			$string = Console::ansiFormat($string, $args);
		}
		return Console::stdout($string);
	}

	/**
	 * Prints a string to STDERR
	 *
	 * You may optionally format the string with ANSI codes by
	 * passing additional parameters using the constants defined in [[yii\helpers\base\Console]].
	 *
	 * Example:
	 * ~~~
	 * $this->stderr('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
	 * ~~~
	 *
	 * @param string $string the string to print
	 * @return int|boolean Number of bytes printed or false on error
	 */
	public function stderr($string)
	{
211
		if ($this->getColors(STDERR)) {
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
			$args = func_get_args();
			array_shift($args);
			$string = Console::ansiFormat($string, $args);
		}
		return fwrite(STDERR, $string);
	}

	/**
	 * Prompts the user for input and validates it
	 *
	 * @param string $text prompt string
	 * @param array $options the options to validate the input:
	 *  - required: whether it is required or not
	 *  - default: default value if no input is inserted by the user
	 *  - pattern: regular expression pattern to validate user input
	 *  - validator: a callable function to validate input. The function must accept two parameters:
	 *      - $input: the user input to validate
	 *      - $error: the error value passed by reference if validation failed.
	 * @return string the user input
	 */
	public function prompt($text, $options = array())
	{
234 235 236 237 238
		if ($this->interactive) {
			return Console::prompt($text, $options);
		} else {
			return isset($options['default']) ? $options['default'] : '';
		}
239 240
	}

Alexander Makarov committed
241 242 243 244 245 246 247 248 249
	/**
	 * Asks user to confirm by typing y or n.
	 *
	 * @param string $message to echo out before waiting for user input
	 * @param boolean $default this value is returned if no selection is made.
	 * @return boolean whether user confirmed
	 */
	public function confirm($message, $default = false)
	{
Qiang Xue committed
250
		if ($this->interactive) {
251
			return Console::confirm($message, $default);
Qiang Xue committed
252 253 254 255 256
		} else {
			return true;
		}
	}

257 258 259 260 261 262 263 264 265
	/**
	 * Gives the user an option to choose from. Giving '?' as an input will show
	 * a list of options to choose from and their explanations.
	 *
	 * @param string $prompt the prompt message
	 * @param array  $options Key-value array of options to choose from
	 *
	 * @return string An option character the user chose
	 */
266
	public function select($prompt, $options = array())
267 268 269 270
	{
		return Console::select($prompt, $options);
	}

Qiang Xue committed
271 272
	/**
	 * Returns the names of the global options for this command.
273
	 * A global option requires the existence of a public member variable whose
Qiang Xue committed
274 275
	 * name is the option name.
	 * Child classes may override this method to specify possible global options.
276 277 278 279
	 *
	 * Note that the values setting via global options are not available
	 * until [[beforeAction()]] is being called.
	 *
Qiang Xue committed
280 281
	 * @return array the names of the global options for this command.
	 */
Qiang Xue committed
282 283
	public function globalOptions()
	{
284
		return array('colors', 'interactive');
Alexander Makarov committed
285
	}
Zander Baldwin committed
286
}