You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

514 lines
18KB

  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 console 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. * where `<route>` is a route to a controller action and the params will be populated as properties of a command.
  25. * See [[options()]] for details.
  26. *
  27. * @property string $help This property is read-only.
  28. * @property string $helpSummary This property is read-only.
  29. *
  30. * @author Qiang Xue <qiang.xue@gmail.com>
  31. * @since 2.0
  32. */
  33. class Controller extends \yii\base\Controller
  34. {
  35. const EXIT_CODE_NORMAL = 0;
  36. const EXIT_CODE_ERROR = 1;
  37. /**
  38. * @var boolean whether to run the command interactively.
  39. */
  40. public $interactive = true;
  41. /**
  42. * @var boolean whether to enable ANSI color in the output.
  43. * If not set, ANSI color will only be enabled for terminals that support it.
  44. */
  45. public $color;
  46. /**
  47. * Returns a value indicating whether ANSI color is enabled.
  48. *
  49. * ANSI color is enabled only if [[color]] is set true or is not set
  50. * and the terminal supports ANSI color.
  51. *
  52. * @param resource $stream the stream to check.
  53. * @return boolean Whether to enable ANSI style in output.
  54. */
  55. public function isColorEnabled($stream = \STDOUT)
  56. {
  57. return $this->color === null ? Console::streamSupportsAnsiColors($stream) : $this->color;
  58. }
  59. /**
  60. * Runs an action with the specified action ID and parameters.
  61. * If the action ID is empty, the method will use [[defaultAction]].
  62. * @param string $id the ID of the action to be executed.
  63. * @param array $params the parameters (name-value pairs) to be passed to the action.
  64. * @return integer the status of the action execution. 0 means normal, other values mean abnormal.
  65. * @throws InvalidRouteException if the requested action ID cannot be resolved into an action successfully.
  66. * @throws Exception if there are unknown options or missing arguments
  67. * @see createAction
  68. */
  69. public function runAction($id, $params = [])
  70. {
  71. if (!empty($params)) {
  72. // populate options here so that they are available in beforeAction().
  73. $options = $this->options($id);
  74. foreach ($params as $name => $value) {
  75. if (in_array($name, $options, true)) {
  76. $default = $this->$name;
  77. $this->$name = is_array($default) ? preg_split('/\s*,\s*/', $value) : $value;
  78. unset($params[$name]);
  79. } elseif (!is_int($name)) {
  80. throw new Exception(Yii::t('yii', 'Unknown option: --{name}', ['name' => $name]));
  81. }
  82. }
  83. }
  84. return parent::runAction($id, $params);
  85. }
  86. /**
  87. * Binds the parameters to the action.
  88. * This method is invoked by [[Action]] when it begins to run with the given parameters.
  89. * This method will first bind the parameters with the [[options()|options]]
  90. * available to the action. It then validates the given arguments.
  91. * @param Action $action the action to be bound with parameters
  92. * @param array $params the parameters to be bound to the action
  93. * @return array the valid parameters that the action can run with.
  94. * @throws Exception if there are unknown options or missing arguments
  95. */
  96. public function bindActionParams($action, $params)
  97. {
  98. if ($action instanceof InlineAction) {
  99. $method = new \ReflectionMethod($this, $action->actionMethod);
  100. } else {
  101. $method = new \ReflectionMethod($action, 'run');
  102. }
  103. $args = array_values($params);
  104. $missing = [];
  105. foreach ($method->getParameters() as $i => $param) {
  106. if ($param->isArray() && isset($args[$i])) {
  107. $args[$i] = preg_split('/\s*,\s*/', $args[$i]);
  108. }
  109. if (!isset($args[$i])) {
  110. if ($param->isDefaultValueAvailable()) {
  111. $args[$i] = $param->getDefaultValue();
  112. } else {
  113. $missing[] = $param->getName();
  114. }
  115. }
  116. }
  117. if (!empty($missing)) {
  118. throw new Exception(Yii::t('yii', 'Missing required arguments: {params}', ['params' => implode(', ', $missing)]));
  119. }
  120. return $args;
  121. }
  122. /**
  123. * Formats a string with ANSI codes
  124. *
  125. * You may pass additional parameters using the constants defined in [[\yii\helpers\Console]].
  126. *
  127. * Example:
  128. *
  129. * ~~~
  130. * echo $this->ansiFormat('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
  131. * ~~~
  132. *
  133. * @param string $string the string to be formatted
  134. * @return string
  135. */
  136. public function ansiFormat($string)
  137. {
  138. if ($this->isColorEnabled()) {
  139. $args = func_get_args();
  140. array_shift($args);
  141. $string = Console::ansiFormat($string, $args);
  142. }
  143. return $string;
  144. }
  145. /**
  146. * Prints a string to STDOUT
  147. *
  148. * You may optionally format the string with ANSI codes by
  149. * passing additional parameters using the constants defined in [[\yii\helpers\Console]].
  150. *
  151. * Example:
  152. *
  153. * ~~~
  154. * $this->stdout('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
  155. * ~~~
  156. *
  157. * @param string $string the string to print
  158. * @return int|boolean Number of bytes printed or false on error
  159. */
  160. public function stdout($string)
  161. {
  162. if ($this->isColorEnabled()) {
  163. $args = func_get_args();
  164. array_shift($args);
  165. $string = Console::ansiFormat($string, $args);
  166. }
  167. return Console::stdout($string);
  168. }
  169. /**
  170. * Prints a string to STDERR
  171. *
  172. * You may optionally format the string with ANSI codes by
  173. * passing additional parameters using the constants defined in [[\yii\helpers\Console]].
  174. *
  175. * Example:
  176. *
  177. * ~~~
  178. * $this->stderr('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
  179. * ~~~
  180. *
  181. * @param string $string the string to print
  182. * @return int|boolean Number of bytes printed or false on error
  183. */
  184. public function stderr($string)
  185. {
  186. if ($this->isColorEnabled(\STDERR)) {
  187. $args = func_get_args();
  188. array_shift($args);
  189. $string = Console::ansiFormat($string, $args);
  190. }
  191. return fwrite(\STDERR, $string);
  192. }
  193. /**
  194. * Prompts the user for input and validates it
  195. *
  196. * @param string $text prompt string
  197. * @param array $options the options to validate the input:
  198. *
  199. * - required: whether it is required or not
  200. * - default: default value if no input is inserted by the user
  201. * - pattern: regular expression pattern to validate user input
  202. * - validator: a callable function to validate input. The function must accept two parameters:
  203. * - $input: the user input to validate
  204. * - $error: the error value passed by reference if validation failed.
  205. * @return string the user input
  206. */
  207. public function prompt($text, $options = [])
  208. {
  209. if ($this->interactive) {
  210. return Console::prompt($text, $options);
  211. } else {
  212. return isset($options['default']) ? $options['default'] : '';
  213. }
  214. }
  215. /**
  216. * Asks user to confirm by typing y or n.
  217. *
  218. * @param string $message to echo out before waiting for user input
  219. * @param boolean $default this value is returned if no selection is made.
  220. * @return boolean whether user confirmed.
  221. * Will return true if [[interactive]] is false.
  222. */
  223. public function confirm($message, $default = false)
  224. {
  225. if ($this->interactive) {
  226. return Console::confirm($message, $default);
  227. } else {
  228. return true;
  229. }
  230. }
  231. /**
  232. * Gives the user an option to choose from. Giving '?' as an input will show
  233. * a list of options to choose from and their explanations.
  234. *
  235. * @param string $prompt the prompt message
  236. * @param array $options Key-value array of options to choose from
  237. *
  238. * @return string An option character the user chose
  239. */
  240. public function select($prompt, $options = [])
  241. {
  242. return Console::select($prompt, $options);
  243. }
  244. /**
  245. * Returns the names of valid options for the action (id)
  246. * An option requires the existence of a public member variable whose
  247. * name is the option name.
  248. * Child classes may override this method to specify possible options.
  249. *
  250. * Note that the values setting via options are not available
  251. * until [[beforeAction()]] is being called.
  252. *
  253. * @param string $actionID the action id of the current request
  254. * @return array the names of the options valid for the action
  255. */
  256. public function options($actionID)
  257. {
  258. // $actionId might be used in subclasses to provide options specific to action id
  259. return ['color', 'interactive'];
  260. }
  261. /**
  262. * Returns one-line short summary describing this controller.
  263. *
  264. * You may override this method to return customized summary.
  265. * The default implementation returns first line from the PHPDoc comment.
  266. *
  267. * @return string
  268. */
  269. public function getHelpSummary()
  270. {
  271. return $this->parseDocCommentSummary(new \ReflectionClass($this));
  272. }
  273. /**
  274. * Returns help information for this controller.
  275. *
  276. * You may override this method to return customized help.
  277. * The default implementation returns help information retrieved from the PHPDoc comment.
  278. * @return string
  279. */
  280. public function getHelp()
  281. {
  282. return $this->parseDocCommentDetail(new \ReflectionClass($this));
  283. }
  284. /**
  285. * Returns a one-line short summary describing the specified action.
  286. * @param Action $action action to get summary for
  287. * @return string a one-line short summary describing the specified action.
  288. */
  289. public function getActionHelpSummary($action)
  290. {
  291. return $this->parseDocCommentSummary($this->getActionMethodReflection($action));
  292. }
  293. /**
  294. * Returns the detailed help information for the specified action.
  295. * @param Action $action action to get help for
  296. * @return string the detailed help information for the specified action.
  297. */
  298. public function getActionHelp($action)
  299. {
  300. return $this->parseDocCommentDetail($this->getActionMethodReflection($action));
  301. }
  302. /**
  303. * Returns the help information for the anonymous arguments for the action.
  304. * The returned value should be an array. The keys are the argument names, and the values are
  305. * the corresponding help information. Each value must be an array of the following structure:
  306. *
  307. * - required: boolean, whether this argument is required.
  308. * - type: string, the PHP type of this argument.
  309. * - default: string, the default value of this argument
  310. * - comment: string, the comment of this argument
  311. *
  312. * The default implementation will return the help information extracted from the doc-comment of
  313. * the parameters corresponding to the action method.
  314. *
  315. * @param Action $action
  316. * @return array the help information of the action arguments
  317. */
  318. public function getActionArgsHelp($action)
  319. {
  320. $method = $this->getActionMethodReflection($action);
  321. $tags = $this->parseDocCommentTags($method);
  322. $params = isset($tags['param']) ? (array) $tags['param'] : [];
  323. $args = [];
  324. foreach ($method->getParameters() as $i => $reflection) {
  325. $name = $reflection->getName();
  326. $tag = isset($params[$i]) ? $params[$i] : '';
  327. if (preg_match('/^([^\s]+)\s+(\$\w+\s+)?(.*)/s', $tag, $matches)) {
  328. $type = $matches[1];
  329. $comment = $matches[3];
  330. } else {
  331. $type = null;
  332. $comment = $tag;
  333. }
  334. if ($reflection->isDefaultValueAvailable()) {
  335. $args[$name] = [
  336. 'required' => false,
  337. 'type' => $type,
  338. 'default' => $reflection->getDefaultValue(),
  339. 'comment' => $comment,
  340. ];
  341. } else {
  342. $args[$name] = [
  343. 'required' => true,
  344. 'type' => $type,
  345. 'default' => null,
  346. 'comment' => $comment,
  347. ];
  348. }
  349. }
  350. return $args;
  351. }
  352. /**
  353. * Returns the help information for the options for the action.
  354. * The returned value should be an array. The keys are the option names, and the values are
  355. * the corresponding help information. Each value must be an array of the following structure:
  356. *
  357. * - type: string, the PHP type of this argument.
  358. * - default: string, the default value of this argument
  359. * - comment: string, the comment of this argument
  360. *
  361. * The default implementation will return the help information extracted from the doc-comment of
  362. * the properties corresponding to the action options.
  363. *
  364. * @param Action $action
  365. * @return array the help information of the action options
  366. */
  367. public function getActionOptionsHelp($action)
  368. {
  369. $optionNames = $this->options($action->id);
  370. if (empty($optionNames)) {
  371. return [];
  372. }
  373. $class = new \ReflectionClass($this);
  374. $options = [];
  375. foreach ($class->getProperties() as $property) {
  376. $name = $property->getName();
  377. if (!in_array($name, $optionNames, true)) {
  378. continue;
  379. }
  380. $defaultValue = $property->getValue($this);
  381. $tags = $this->parseDocCommentTags($property);
  382. if (isset($tags['var']) || isset($tags['property'])) {
  383. $doc = isset($tags['var']) ? $tags['var'] : $tags['property'];
  384. if (is_array($doc)) {
  385. $doc = reset($doc);
  386. }
  387. if (preg_match('/^([^\s]+)(.*)/s', $doc, $matches)) {
  388. $type = $matches[1];
  389. $comment = $matches[2];
  390. } else {
  391. $type = null;
  392. $comment = $doc;
  393. }
  394. $options[$name] = [
  395. 'type' => $type,
  396. 'default' => $defaultValue,
  397. 'comment' => $comment,
  398. ];
  399. } else {
  400. $options[$name] = [
  401. 'type' => null,
  402. 'default' => $defaultValue,
  403. 'comment' => '',
  404. ];
  405. }
  406. }
  407. return $options;
  408. }
  409. private $_reflections = [];
  410. /**
  411. * @param Action $action
  412. * @return \ReflectionMethod
  413. */
  414. protected function getActionMethodReflection($action)
  415. {
  416. if (!isset($this->_reflections[$action->id])) {
  417. if ($action instanceof InlineAction) {
  418. $this->_reflections[$action->id] = new \ReflectionMethod($this, $action->actionMethod);
  419. } else {
  420. $this->_reflections[$action->id] = new \ReflectionMethod($action, 'run');
  421. }
  422. }
  423. return $this->_reflections[$action->id];
  424. }
  425. /**
  426. * Parses the comment block into tags.
  427. * @param \Reflector $reflection the comment block
  428. * @return array the parsed tags
  429. */
  430. protected function parseDocCommentTags($reflection)
  431. {
  432. $comment = $reflection->getDocComment();
  433. $comment = "@description \n" . strtr(trim(preg_replace('/^\s*\**( |\t)?/m', '', trim($comment, '/'))), "\r", '');
  434. $parts = preg_split('/^\s*@/m', $comment, -1, PREG_SPLIT_NO_EMPTY);
  435. $tags = [];
  436. foreach ($parts as $part) {
  437. if (preg_match('/^(\w+)(.*)/ms', trim($part), $matches)) {
  438. $name = $matches[1];
  439. if (!isset($tags[$name])) {
  440. $tags[$name] = trim($matches[2]);
  441. } elseif (is_array($tags[$name])) {
  442. $tags[$name][] = trim($matches[2]);
  443. } else {
  444. $tags[$name] = [$tags[$name], trim($matches[2])];
  445. }
  446. }
  447. }
  448. return $tags;
  449. }
  450. /**
  451. * Returns the first line of docblock.
  452. *
  453. * @param \Reflector $reflection
  454. * @return string
  455. */
  456. protected function parseDocCommentSummary($reflection)
  457. {
  458. $docLines = preg_split('~\R~u', $reflection->getDocComment());
  459. if (isset($docLines[1])) {
  460. return trim($docLines[1], "\t *");
  461. }
  462. return '';
  463. }
  464. /**
  465. * Returns full description from the docblock.
  466. *
  467. * @param \Reflector $reflection
  468. * @return string
  469. */
  470. protected function parseDocCommentDetail($reflection)
  471. {
  472. $comment = strtr(trim(preg_replace('/^\s*\**( |\t)?/m', '', trim($reflection->getDocComment(), '/'))), "\r", '');
  473. if (preg_match('/^\s*@\w+/m', $comment, $matches, PREG_OFFSET_CAPTURE)) {
  474. $comment = trim(substr($comment, 0, $matches[0][1]));
  475. }
  476. if ($comment !== '') {
  477. return rtrim(Console::renderColoredString(Console::markdownToAnsi($comment)));
  478. }
  479. return '';
  480. }
  481. }