Controller.php 28 KB

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