選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

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