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.

624 lines
21KB

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