Controller.php 23 KB

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