Controller.php 7.97 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
	 * @var boolean whether to enable ANSI color in the output.
39
	 * If not set, ANSI color will only be enabled for terminals that support it.
40
	 */
41
	public $color;
42 43

	/**
44
	 * Returns a value indicating whether ANSI color is enabled.
45
	 *
46 47
	 * ANSI color is enabled only if [[color]] is set true or is not set
	 * and the terminal supports ANSI color.
48 49
	 *
	 * @param resource $stream the stream to check.
50 51
	 * @return boolean Whether to enable ANSI style in output.
	 */
52
	public function isColorEnabled($stream = STDOUT)
53
	{
54
		return $this->color ===  null ? Console::streamSupportsAnsiColors($stream) : $this->color;
55
	}
56

Qiang Xue committed
57 58 59 60 61 62 63
	/**
	 * 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.
64
	 * @throws Exception if there are unknown options or missing arguments
Qiang Xue committed
65 66
	 * @see createAction
	 */
Alexander Makarov committed
67
	public function runAction($id, $params = [])
Qiang Xue committed
68
	{
69
		if (!empty($params)) {
70
			// populate global options here so that they are available in beforeAction().
Qiang Xue committed
71
			$options = $this->globalOptions();
Qiang Xue committed
72
			foreach ($params as $name => $value) {
Qiang Xue committed
73
				if (in_array($name, $options, true)) {
74 75
					$default = $this->$name;
					$this->$name = is_array($default) ? preg_split('/\s*,\s*/', $value) : $value;
Qiang Xue committed
76
					unset($params[$name]);
77 78
				} elseif (!is_int($name)) {
					throw new Exception(Yii::t('yii', 'Unknown option: --{name}', ['name' => $name]));
Qiang Xue committed
79 80 81 82 83 84
				}
			}
		}
		return parent::runAction($id, $params);
	}

Qiang Xue committed
85
	/**
Qiang Xue committed
86 87 88 89 90 91 92 93
	 * 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
94
	 */
Qiang Xue committed
95
	public function bindActionParams($action, $params)
Qiang Xue committed
96
	{
Qiang Xue committed
97 98 99 100 101 102
		if ($action instanceof InlineAction) {
			$method = new \ReflectionMethod($this, $action->actionMethod);
		} else {
			$method = new \ReflectionMethod($action, 'run');
		}

103 104
		$args = array_values($params);

Alexander Makarov committed
105
		$missing = [];
Qiang Xue committed
106
		foreach ($method->getParameters() as $i => $param) {
107 108 109
			if ($param->isArray() && isset($args[$i])) {
				$args[$i] = preg_split('/\s*,\s*/', $args[$i]);
			}
Qiang Xue committed
110 111 112 113
			if (!isset($args[$i])) {
				if ($param->isDefaultValueAvailable()) {
					$args[$i] = $param->getDefaultValue();
				} else {
114
					$missing[] = $param->getName();
Qiang Xue committed
115 116 117 118
				}
			}
		}

119
		if (!empty($missing)) {
Alexander Makarov committed
120
			throw new Exception(Yii::t('yii', 'Missing required arguments: {params}', ['params' => implode(', ', $missing)]));
Alexander Makarov committed
121
		}
Qiang Xue committed
122 123

		return $args;
Alexander Makarov committed
124
	}
Alexander Makarov committed
125

126 127 128
	/**
	 * Formats a string with ANSI codes
	 *
129
	 * You may pass additional parameters using the constants defined in [[\yii\helpers\Console]].
130 131
	 *
	 * Example:
132
	 *
133
	 * ~~~
134
	 * echo $this->ansiFormat('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
135 136 137 138 139
	 * ~~~
	 *
	 * @param string $string the string to be formatted
	 * @return string
	 */
140
	public function ansiFormat($string)
141
	{
142
		if ($this->isColorEnabled()) {
143 144 145 146 147 148 149 150 151 152 153
			$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
154
	 * passing additional parameters using the constants defined in [[\yii\helpers\Console]].
155 156
	 *
	 * Example:
157
	 *
158 159 160 161 162 163 164 165 166
	 * ~~~
	 * $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)
	{
167
		if ($this->isColorEnabled()) {
168 169 170 171 172 173 174 175 176 177 178
			$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
179
	 * passing additional parameters using the constants defined in [[\yii\helpers\Console]].
180 181
	 *
	 * Example:
182
	 *
183 184 185 186 187 188 189 190 191
	 * ~~~
	 * $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)
	{
192
		if ($this->isColorEnabled(STDERR)) {
193 194 195 196 197 198 199 200 201 202 203 204
			$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:
205
	 *
206 207 208 209 210 211 212 213
	 *  - 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
	 */
Alexander Makarov committed
214
	public function prompt($text, $options = [])
215
	{
216 217 218 219 220
		if ($this->interactive) {
			return Console::prompt($text, $options);
		} else {
			return isset($options['default']) ? $options['default'] : '';
		}
221 222
	}

Alexander Makarov committed
223 224 225 226 227
	/**
	 * 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.
228 229
	 * @return boolean whether user confirmed.
	 * Will return true if [[interactive]] is false.
Alexander Makarov committed
230 231 232
	 */
	public function confirm($message, $default = false)
	{
Qiang Xue committed
233
		if ($this->interactive) {
234
			return Console::confirm($message, $default);
Qiang Xue committed
235 236 237 238 239
		} else {
			return true;
		}
	}

240 241 242 243 244 245 246 247 248
	/**
	 * 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
	 */
Alexander Makarov committed
249
	public function select($prompt, $options = [])
250 251 252 253
	{
		return Console::select($prompt, $options);
	}

Qiang Xue committed
254 255
	/**
	 * Returns the names of the global options for this command.
256
	 * A global option requires the existence of a public member variable whose
Qiang Xue committed
257 258
	 * name is the option name.
	 * Child classes may override this method to specify possible global options.
259 260 261 262
	 *
	 * Note that the values setting via global options are not available
	 * until [[beforeAction()]] is being called.
	 *
Qiang Xue committed
263 264
	 * @return array the names of the global options for this command.
	 */
Qiang Xue committed
265 266
	public function globalOptions()
	{
Alexander Makarov committed
267
		return ['color', 'interactive'];
Alexander Makarov committed
268
	}
Zander Baldwin committed
269
}