Controller.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  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 bool whether to run the command interactively.
  43. */
  44. public $interactive = true;
  45. /**
  46. * @var bool 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 bool 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 bool 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 int 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->getUniqueId() . '/' . $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 int|bool 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 int|bool 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. }
  261. return isset($options['default']) ? $options['default'] : '';
  262. }
  263. /**
  264. * Asks user to confirm by typing y or n.
  265. *
  266. * A typical usage looks like the following:
  267. *
  268. * ```php
  269. * if ($this->confirm("Are you sure?")) {
  270. * echo "user typed yes\n";
  271. * } else {
  272. * echo "user typed no\n";
  273. * }
  274. * ```
  275. *
  276. * @param string $message to echo out before waiting for user input
  277. * @param bool $default this value is returned if no selection is made.
  278. * @return bool whether user confirmed.
  279. * Will return true if [[interactive]] is false.
  280. */
  281. public function confirm($message, $default = false)
  282. {
  283. if ($this->interactive) {
  284. return Console::confirm($message, $default);
  285. }
  286. return true;
  287. }
  288. /**
  289. * Gives the user an option to choose from. Giving '?' as an input will show
  290. * a list of options to choose from and their explanations.
  291. *
  292. * @param string $prompt the prompt message
  293. * @param array $options Key-value array of options to choose from
  294. *
  295. * @return string An option character the user chose
  296. */
  297. public function select($prompt, $options = [])
  298. {
  299. return Console::select($prompt, $options);
  300. }
  301. /**
  302. * Returns the names of valid options for the action (id)
  303. * An option requires the existence of a public member variable whose
  304. * name is the option name.
  305. * Child classes may override this method to specify possible options.
  306. *
  307. * Note that the values setting via options are not available
  308. * until [[beforeAction()]] is being called.
  309. *
  310. * @param string $actionID the action id of the current request
  311. * @return string[] the names of the options valid for the action
  312. */
  313. public function options($actionID)
  314. {
  315. // $actionId might be used in subclasses to provide options specific to action id
  316. return ['color', 'interactive', 'help'];
  317. }
  318. /**
  319. * Returns option alias names.
  320. * Child classes may override this method to specify alias options.
  321. *
  322. * @return array the options alias names valid for the action
  323. * where the keys is alias name for option and value is option name.
  324. *
  325. * @since 2.0.8
  326. * @see options()
  327. */
  328. public function optionAliases()
  329. {
  330. return [
  331. 'h' => 'help'
  332. ];
  333. }
  334. /**
  335. * Returns properties corresponding to the options for the action id
  336. * Child classes may override this method to specify possible properties.
  337. *
  338. * @param string $actionID the action id of the current request
  339. * @return array properties corresponding to the options for the action
  340. */
  341. public function getOptionValues($actionID)
  342. {
  343. // $actionId might be used in subclasses to provide properties specific to action id
  344. $properties = [];
  345. foreach ($this->options($this->action->id) as $property) {
  346. $properties[$property] = $this->$property;
  347. }
  348. return $properties;
  349. }
  350. /**
  351. * Returns the names of valid options passed during execution.
  352. *
  353. * @return array the names of the options passed during execution
  354. */
  355. public function getPassedOptions()
  356. {
  357. return $this->_passedOptions;
  358. }
  359. /**
  360. * Returns the properties corresponding to the passed options
  361. *
  362. * @return array the properties corresponding to the passed options
  363. */
  364. public function getPassedOptionValues()
  365. {
  366. $properties = [];
  367. foreach ($this->_passedOptions as $property) {
  368. $properties[$property] = $this->$property;
  369. }
  370. return $properties;
  371. }
  372. /**
  373. * Returns one-line short summary describing this controller.
  374. *
  375. * You may override this method to return customized summary.
  376. * The default implementation returns first line from the PHPDoc comment.
  377. *
  378. * @return string
  379. */
  380. public function getHelpSummary()
  381. {
  382. return $this->parseDocCommentSummary(new \ReflectionClass($this));
  383. }
  384. /**
  385. * Returns help information for this controller.
  386. *
  387. * You may override this method to return customized help.
  388. * The default implementation returns help information retrieved from the PHPDoc comment.
  389. * @return string
  390. */
  391. public function getHelp()
  392. {
  393. return $this->parseDocCommentDetail(new \ReflectionClass($this));
  394. }
  395. /**
  396. * Returns a one-line short summary describing the specified action.
  397. * @param Action $action action to get summary for
  398. * @return string a one-line short summary describing the specified action.
  399. */
  400. public function getActionHelpSummary($action)
  401. {
  402. return $this->parseDocCommentSummary($this->getActionMethodReflection($action));
  403. }
  404. /**
  405. * Returns the detailed help information for the specified action.
  406. * @param Action $action action to get help for
  407. * @return string the detailed help information for the specified action.
  408. */
  409. public function getActionHelp($action)
  410. {
  411. return $this->parseDocCommentDetail($this->getActionMethodReflection($action));
  412. }
  413. /**
  414. * Returns the help information for the anonymous arguments for the action.
  415. * The returned value should be an array. The keys are the argument names, and the values are
  416. * the corresponding help information. Each value must be an array of the following structure:
  417. *
  418. * - required: boolean, whether this argument is required.
  419. * - type: string, the PHP type of this argument.
  420. * - default: string, the default value of this argument
  421. * - comment: string, the comment of this argument
  422. *
  423. * The default implementation will return the help information extracted from the doc-comment of
  424. * the parameters corresponding to the action method.
  425. *
  426. * @param Action $action
  427. * @return array the help information of the action arguments
  428. */
  429. public function getActionArgsHelp($action)
  430. {
  431. $method = $this->getActionMethodReflection($action);
  432. $tags = $this->parseDocCommentTags($method);
  433. $params = isset($tags['param']) ? (array) $tags['param'] : [];
  434. $args = [];
  435. /** @var \ReflectionParameter $reflection */
  436. foreach ($method->getParameters() as $i => $reflection) {
  437. $name = $reflection->getName();
  438. $tag = isset($params[$i]) ? $params[$i] : '';
  439. if (preg_match('/^(\S+)\s+(\$\w+\s+)?(.*)/s', $tag, $matches)) {
  440. $type = $matches[1];
  441. $comment = $matches[3];
  442. } else {
  443. $type = null;
  444. $comment = $tag;
  445. }
  446. if ($reflection->isDefaultValueAvailable()) {
  447. $args[$name] = [
  448. 'required' => false,
  449. 'type' => $type,
  450. 'default' => $reflection->getDefaultValue(),
  451. 'comment' => $comment,
  452. ];
  453. } else {
  454. $args[$name] = [
  455. 'required' => true,
  456. 'type' => $type,
  457. 'default' => null,
  458. 'comment' => $comment,
  459. ];
  460. }
  461. }
  462. return $args;
  463. }
  464. /**
  465. * Returns the help information for the options for the action.
  466. * The returned value should be an array. The keys are the option names, and the values are
  467. * the corresponding help information. Each value must be an array of the following structure:
  468. *
  469. * - type: string, the PHP type of this argument.
  470. * - default: string, the default value of this argument
  471. * - comment: string, the comment of this argument
  472. *
  473. * The default implementation will return the help information extracted from the doc-comment of
  474. * the properties corresponding to the action options.
  475. *
  476. * @param Action $action
  477. * @return array the help information of the action options
  478. */
  479. public function getActionOptionsHelp($action)
  480. {
  481. $optionNames = $this->options($action->id);
  482. if (empty($optionNames)) {
  483. return [];
  484. }
  485. $class = new \ReflectionClass($this);
  486. $options = [];
  487. foreach ($class->getProperties() as $property) {
  488. $name = $property->getName();
  489. if (!in_array($name, $optionNames, true)) {
  490. continue;
  491. }
  492. $defaultValue = $property->getValue($this);
  493. $tags = $this->parseDocCommentTags($property);
  494. if (isset($tags['var']) || isset($tags['property'])) {
  495. $doc = isset($tags['var']) ? $tags['var'] : $tags['property'];
  496. if (is_array($doc)) {
  497. $doc = reset($doc);
  498. }
  499. if (preg_match('/^(\S+)(.*)/s', $doc, $matches)) {
  500. $type = $matches[1];
  501. $comment = $matches[2];
  502. } else {
  503. $type = null;
  504. $comment = $doc;
  505. }
  506. $options[$name] = [
  507. 'type' => $type,
  508. 'default' => $defaultValue,
  509. 'comment' => $comment,
  510. ];
  511. } else {
  512. $options[$name] = [
  513. 'type' => null,
  514. 'default' => $defaultValue,
  515. 'comment' => '',
  516. ];
  517. }
  518. }
  519. return $options;
  520. }
  521. private $_reflections = [];
  522. /**
  523. * @param Action $action
  524. * @return \ReflectionMethod
  525. */
  526. protected function getActionMethodReflection($action)
  527. {
  528. if (!isset($this->_reflections[$action->id])) {
  529. if ($action instanceof InlineAction) {
  530. $this->_reflections[$action->id] = new \ReflectionMethod($this, $action->actionMethod);
  531. } else {
  532. $this->_reflections[$action->id] = new \ReflectionMethod($action, 'run');
  533. }
  534. }
  535. return $this->_reflections[$action->id];
  536. }
  537. /**
  538. * Parses the comment block into tags.
  539. * @param \Reflector $reflection the comment block
  540. * @return array the parsed tags
  541. */
  542. protected function parseDocCommentTags($reflection)
  543. {
  544. $comment = $reflection->getDocComment();
  545. $comment = "@description \n" . strtr(trim(preg_replace('/^\s*\**( |\t)?/m', '', trim($comment, '/'))), "\r", '');
  546. $parts = preg_split('/^\s*@/m', $comment, -1, PREG_SPLIT_NO_EMPTY);
  547. $tags = [];
  548. foreach ($parts as $part) {
  549. if (preg_match('/^(\w+)(.*)/ms', trim($part), $matches)) {
  550. $name = $matches[1];
  551. if (!isset($tags[$name])) {
  552. $tags[$name] = trim($matches[2]);
  553. } elseif (is_array($tags[$name])) {
  554. $tags[$name][] = trim($matches[2]);
  555. } else {
  556. $tags[$name] = [$tags[$name], trim($matches[2])];
  557. }
  558. }
  559. }
  560. return $tags;
  561. }
  562. /**
  563. * Returns the first line of docblock.
  564. *
  565. * @param \Reflector $reflection
  566. * @return string
  567. */
  568. protected function parseDocCommentSummary($reflection)
  569. {
  570. $docLines = preg_split('~\R~u', $reflection->getDocComment());
  571. if (isset($docLines[1])) {
  572. return trim($docLines[1], "\t *");
  573. }
  574. return '';
  575. }
  576. /**
  577. * Returns full description from the docblock.
  578. *
  579. * @param \Reflector $reflection
  580. * @return string
  581. */
  582. protected function parseDocCommentDetail($reflection)
  583. {
  584. $comment = strtr(trim(preg_replace('/^\s*\**( |\t)?/m', '', trim($reflection->getDocComment(), '/'))), "\r", '');
  585. if (preg_match('/^\s*@\w+/m', $comment, $matches, PREG_OFFSET_CAPTURE)) {
  586. $comment = trim(substr($comment, 0, $matches[0][1]));
  587. }
  588. if ($comment !== '') {
  589. return rtrim(Console::renderColoredString(Console::markdownToAnsi($comment)));
  590. }
  591. return '';
  592. }
  593. }