Controller.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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\console;
  8. use Yii;
  9. use yii\base\Action;
  10. use yii\base\InlineAction;
  11. use yii\base\InvalidRouteException;
  12. use yii\helpers\Console;
  13. /**
  14. * Controller is the base class of console command classes.
  15. *
  16. * A controller consists of one or several actions known as sub-commands.
  17. * Users call a console command by specifying the corresponding route which identifies a controller action.
  18. * The `yii` program is used when calling a console command, like the following:
  19. *
  20. * ~~~
  21. * yii <route> [--param1=value1 --param2 ...]
  22. * ~~~
  23. *
  24. * @author Qiang Xue <[email protected]>
  25. * @since 2.0
  26. */
  27. class Controller extends \yii\base\Controller
  28. {
  29. /**
  30. * @var boolean whether to run the command interactively.
  31. */
  32. public $interactive = true;
  33. /**
  34. * @var boolean whether to enable ANSI color in the output.
  35. * If not set, ANSI color will only be enabled for terminals that support it.
  36. */
  37. public $color;
  38. /**
  39. * Returns a value indicating whether ANSI color is enabled.
  40. *
  41. * ANSI color is enabled only if [[color]] is set true or is not set
  42. * and the terminal supports ANSI color.
  43. *
  44. * @param resource $stream the stream to check.
  45. * @return boolean Whether to enable ANSI style in output.
  46. */
  47. public function isColorEnabled($stream = STDOUT)
  48. {
  49. return $this->color === null ? Console::streamSupportsAnsiColors($stream) : $this->color;
  50. }
  51. /**
  52. * Runs an action with the specified action ID and parameters.
  53. * If the action ID is empty, the method will use [[defaultAction]].
  54. * @param string $id the ID of the action to be executed.
  55. * @param array $params the parameters (name-value pairs) to be passed to the action.
  56. * @return integer the status of the action execution. 0 means normal, other values mean abnormal.
  57. * @throws InvalidRouteException if the requested action ID cannot be resolved into an action successfully.
  58. * @see createAction
  59. */
  60. public function runAction($id, $params = [])
  61. {
  62. if (!empty($params)) {
  63. $options = $this->globalOptions();
  64. foreach ($params as $name => $value) {
  65. if (in_array($name, $options, true)) {
  66. $this->$name = $value;
  67. unset($params[$name]);
  68. }
  69. }
  70. }
  71. return parent::runAction($id, $params);
  72. }
  73. /**
  74. * Binds the parameters to the action.
  75. * This method is invoked by [[Action]] when it begins to run with the given parameters.
  76. * This method will first bind the parameters with the [[globalOptions()|global options]]
  77. * available to the action. It then validates the given arguments.
  78. * @param Action $action the action to be bound with parameters
  79. * @param array $params the parameters to be bound to the action
  80. * @return array the valid parameters that the action can run with.
  81. * @throws Exception if there are unknown options or missing arguments
  82. */
  83. public function bindActionParams($action, $params)
  84. {
  85. $args = [];
  86. if (!empty($params)) {
  87. $options = $this->globalOptions();
  88. foreach ($params as $name => $value) {
  89. if (in_array($name, $options, true)) {
  90. $this->$name = $value;
  91. } elseif (is_int($name)) {
  92. $args[] = $value;
  93. } else {
  94. throw new Exception(Yii::t('yii', 'Unknown option: --{name}', ['name' => $name]));
  95. }
  96. }
  97. }
  98. if ($action instanceof InlineAction) {
  99. $method = new \ReflectionMethod($this, $action->actionMethod);
  100. } else {
  101. $method = new \ReflectionMethod($action, 'run');
  102. }
  103. $missing = [];
  104. foreach ($method->getParameters() as $i => $param) {
  105. if ($param->isArray() && isset($args[$i])) {
  106. $args[$i] = preg_split('/\s*,\s*/', $args[$i]);
  107. }
  108. if (!isset($args[$i])) {
  109. if ($param->isDefaultValueAvailable()) {
  110. $args[$i] = $param->getDefaultValue();
  111. } else {
  112. $missing[] = $param->getName();
  113. }
  114. }
  115. }
  116. if (!empty($missing)) {
  117. throw new Exception(Yii::t('yii', 'Missing required arguments: {params}', ['params' => implode(', ', $missing)]));
  118. }
  119. return $args;
  120. }
  121. /**
  122. * Formats a string with ANSI codes
  123. *
  124. * You may pass additional parameters using the constants defined in [[yii\helpers\Console]].
  125. *
  126. * Example:
  127. *
  128. * ~~~
  129. * echo $this->ansiFormat('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
  130. * ~~~
  131. *
  132. * @param string $string the string to be formatted
  133. * @return string
  134. */
  135. public function ansiFormat($string)
  136. {
  137. if ($this->isColorEnabled()) {
  138. $args = func_get_args();
  139. array_shift($args);
  140. $string = Console::ansiFormat($string, $args);
  141. }
  142. return $string;
  143. }
  144. /**
  145. * Prints a string to STDOUT
  146. *
  147. * You may optionally format the string with ANSI codes by
  148. * passing additional parameters using the constants defined in [[yii\helpers\Console]].
  149. *
  150. * Example:
  151. *
  152. * ~~~
  153. * $this->stdout('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
  154. * ~~~
  155. *
  156. * @param string $string the string to print
  157. * @return int|boolean Number of bytes printed or false on error
  158. */
  159. public function stdout($string)
  160. {
  161. if ($this->isColorEnabled()) {
  162. $args = func_get_args();
  163. array_shift($args);
  164. $string = Console::ansiFormat($string, $args);
  165. }
  166. return Console::stdout($string);
  167. }
  168. /**
  169. * Prints a string to STDERR
  170. *
  171. * You may optionally format the string with ANSI codes by
  172. * passing additional parameters using the constants defined in [[yii\helpers\Console]].
  173. *
  174. * Example:
  175. *
  176. * ~~~
  177. * $this->stderr('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
  178. * ~~~
  179. *
  180. * @param string $string the string to print
  181. * @return int|boolean Number of bytes printed or false on error
  182. */
  183. public function stderr($string)
  184. {
  185. if ($this->isColorEnabled(STDERR)) {
  186. $args = func_get_args();
  187. array_shift($args);
  188. $string = Console::ansiFormat($string, $args);
  189. }
  190. return fwrite(STDERR, $string);
  191. }
  192. /**
  193. * Prompts the user for input and validates it
  194. *
  195. * @param string $text prompt string
  196. * @param array $options the options to validate the input:
  197. *
  198. * - required: whether it is required or not
  199. * - default: default value if no input is inserted by the user
  200. * - pattern: regular expression pattern to validate user input
  201. * - validator: a callable function to validate input. The function must accept two parameters:
  202. * - $input: the user input to validate
  203. * - $error: the error value passed by reference if validation failed.
  204. * @return string the user input
  205. */
  206. public function prompt($text, $options = [])
  207. {
  208. if ($this->interactive) {
  209. return Console::prompt($text, $options);
  210. } else {
  211. return isset($options['default']) ? $options['default'] : '';
  212. }
  213. }
  214. /**
  215. * Asks user to confirm by typing y or n.
  216. *
  217. * @param string $message to echo out before waiting for user input
  218. * @param boolean $default this value is returned if no selection is made.
  219. * @return boolean whether user confirmed.
  220. * Will return true if [[interactive]] is false.
  221. */
  222. public function confirm($message, $default = false)
  223. {
  224. if ($this->interactive) {
  225. return Console::confirm($message, $default);
  226. } else {
  227. return true;
  228. }
  229. }
  230. /**
  231. * Gives the user an option to choose from. Giving '?' as an input will show
  232. * a list of options to choose from and their explanations.
  233. *
  234. * @param string $prompt the prompt message
  235. * @param array $options Key-value array of options to choose from
  236. *
  237. * @return string An option character the user chose
  238. */
  239. public function select($prompt, $options = [])
  240. {
  241. return Console::select($prompt, $options);
  242. }
  243. /**
  244. * Returns the names of the global options for this command.
  245. * A global option requires the existence of a public member variable whose
  246. * name is the option name.
  247. * Child classes may override this method to specify possible global options.
  248. *
  249. * Note that the values setting via global options are not available
  250. * until [[beforeAction()]] is being called.
  251. *
  252. * @return array the names of the global options for this command.
  253. */
  254. public function globalOptions()
  255. {
  256. return ['color', 'interactive'];
  257. }
  258. }