Controller.php 23 KB

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