Controller.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  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. $args = [];
  186. $missing = [];
  187. $actionParams = [];
  188. $requestedParams = [];
  189. foreach ($method->getParameters() as $i => $param) {
  190. $name = $param->getName();
  191. $key = null;
  192. if (array_key_exists($i, $params)) {
  193. $key = $i;
  194. } elseif (array_key_exists($name, $params)) {
  195. $key = $name;
  196. }
  197. if ($key !== null) {
  198. if (PHP_VERSION_ID >= 80000) {
  199. $isArray = ($type = $param->getType()) instanceof \ReflectionNamedType && $type->getName() === 'array';
  200. } else {
  201. $isArray = $param->isArray();
  202. }
  203. if ($isArray) {
  204. $params[$key] = $params[$key] === '' ? [] : preg_split('/\s*,\s*/', $params[$key]);
  205. }
  206. $args[] = $actionParams[$key] = $params[$key];
  207. unset($params[$key]);
  208. } elseif (
  209. PHP_VERSION_ID >= 70100
  210. && ($type = $param->getType()) !== null
  211. && $type instanceof \ReflectionNamedType
  212. && !$type->isBuiltin()
  213. ) {
  214. try {
  215. $this->bindInjectedParams($type, $name, $args, $requestedParams);
  216. } catch (\yii\base\Exception $e) {
  217. throw new Exception($e->getMessage());
  218. }
  219. } elseif ($param->isDefaultValueAvailable()) {
  220. $args[] = $actionParams[$i] = $param->getDefaultValue();
  221. } else {
  222. $missing[] = $name;
  223. }
  224. }
  225. if (!empty($missing)) {
  226. throw new Exception(Yii::t('yii', 'Missing required arguments: {params}', ['params' => implode(', ', $missing)]));
  227. }
  228. // We use a different array here, specifically one that doesn't contain service instances but descriptions instead.
  229. if (\Yii::$app->requestedParams === null) {
  230. \Yii::$app->requestedParams = array_merge($actionParams, $requestedParams);
  231. }
  232. return array_merge($args, $params);
  233. }
  234. /**
  235. * Formats a string with ANSI codes.
  236. *
  237. * You may pass additional parameters using the constants defined in [[\yii\helpers\Console]].
  238. *
  239. * Example:
  240. *
  241. * ```
  242. * echo $this->ansiFormat('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
  243. * ```
  244. *
  245. * @param string $string the string to be formatted
  246. * @return string
  247. */
  248. public function ansiFormat($string)
  249. {
  250. if ($this->isColorEnabled()) {
  251. $args = func_get_args();
  252. array_shift($args);
  253. $string = Console::ansiFormat($string, $args);
  254. }
  255. return $string;
  256. }
  257. /**
  258. * Prints a string to STDOUT.
  259. *
  260. * You may optionally format the string with ANSI codes by
  261. * passing additional parameters using the constants defined in [[\yii\helpers\Console]].
  262. *
  263. * Example:
  264. *
  265. * ```
  266. * $this->stdout('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
  267. * ```
  268. *
  269. * @param string $string the string to print
  270. * @param int ...$args additional parameters to decorate the output
  271. * @return int|bool Number of bytes printed or false on error
  272. */
  273. public function stdout($string)
  274. {
  275. if ($this->isColorEnabled()) {
  276. $args = func_get_args();
  277. array_shift($args);
  278. $string = Console::ansiFormat($string, $args);
  279. }
  280. return Console::stdout($string);
  281. }
  282. /**
  283. * Prints a string to STDERR.
  284. *
  285. * You may optionally format the string with ANSI codes by
  286. * passing additional parameters using the constants defined in [[\yii\helpers\Console]].
  287. *
  288. * Example:
  289. *
  290. * ```
  291. * $this->stderr('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
  292. * ```
  293. *
  294. * @param string $string the string to print
  295. * @param int ...$args additional parameters to decorate the output
  296. * @return int|bool Number of bytes printed or false on error
  297. */
  298. public function stderr($string)
  299. {
  300. if ($this->isColorEnabled(\STDERR)) {
  301. $args = func_get_args();
  302. array_shift($args);
  303. $string = Console::ansiFormat($string, $args);
  304. }
  305. return fwrite(\STDERR, $string);
  306. }
  307. /**
  308. * Prompts the user for input and validates it.
  309. *
  310. * @param string $text prompt string
  311. * @param array $options the options to validate the input:
  312. *
  313. * - required: whether it is required or not
  314. * - default: default value if no input is inserted by the user
  315. * - pattern: regular expression pattern to validate user input
  316. * - validator: a callable function to validate input. The function must accept two parameters:
  317. * - $input: the user input to validate
  318. * - $error: the error value passed by reference if validation failed.
  319. *
  320. * An example of how to use the prompt method with a validator function.
  321. *
  322. * ```php
  323. * $code = $this->prompt('Enter 4-Chars-Pin', ['required' => true, 'validator' => function($input, &$error) {
  324. * if (strlen($input) !== 4) {
  325. * $error = 'The Pin must be exactly 4 chars!';
  326. * return false;
  327. * }
  328. * return true;
  329. * }]);
  330. * ```
  331. *
  332. * @return string the user input
  333. */
  334. public function prompt($text, $options = [])
  335. {
  336. if ($this->interactive) {
  337. return Console::prompt($text, $options);
  338. }
  339. return isset($options['default']) ? $options['default'] : '';
  340. }
  341. /**
  342. * Asks user to confirm by typing y or n.
  343. *
  344. * A typical usage looks like the following:
  345. *
  346. * ```php
  347. * if ($this->confirm("Are you sure?")) {
  348. * echo "user typed yes\n";
  349. * } else {
  350. * echo "user typed no\n";
  351. * }
  352. * ```
  353. *
  354. * @param string $message to echo out before waiting for user input
  355. * @param bool $default this value is returned if no selection is made.
  356. * @return bool whether user confirmed.
  357. * Will return true if [[interactive]] is false.
  358. */
  359. public function confirm($message, $default = false)
  360. {
  361. if ($this->interactive) {
  362. return Console::confirm($message, $default);
  363. }
  364. return true;
  365. }
  366. /**
  367. * Gives the user an option to choose from. Giving '?' as an input will show
  368. * a list of options to choose from and their explanations.
  369. *
  370. * @param string $prompt the prompt message
  371. * @param array $options Key-value array of options to choose from
  372. * @param string|null $default value to use when the user doesn't provide an option.
  373. * If the default is `null`, the user is required to select an option.
  374. *
  375. * @return string An option character the user chose
  376. * @since 2.0.49 Added the $default argument
  377. */
  378. public function select($prompt, $options = [], $default = null)
  379. {
  380. if ($this->interactive) {
  381. return Console::select($prompt, $options, $default);
  382. }
  383. return $default;
  384. }
  385. /**
  386. * Returns the names of valid options for the action (id)
  387. * An option requires the existence of a public member variable whose
  388. * name is the option name.
  389. * Child classes may override this method to specify possible options.
  390. *
  391. * Note that the values setting via options are not available
  392. * until [[beforeAction()]] is being called.
  393. *
  394. * @param string $actionID the action id of the current request
  395. * @return string[] the names of the options valid for the action
  396. */
  397. public function options($actionID)
  398. {
  399. // $actionId might be used in subclasses to provide options specific to action id
  400. return ['color', 'interactive', 'help', 'silentExitOnException'];
  401. }
  402. /**
  403. * Returns option alias names.
  404. * Child classes may override this method to specify alias options.
  405. *
  406. * @return array the options alias names valid for the action
  407. * where the keys is alias name for option and value is option name.
  408. *
  409. * @since 2.0.8
  410. * @see options()
  411. */
  412. public function optionAliases()
  413. {
  414. return [
  415. 'h' => 'help',
  416. ];
  417. }
  418. /**
  419. * Returns properties corresponding to the options for the action id
  420. * Child classes may override this method to specify possible properties.
  421. *
  422. * @param string $actionID the action id of the current request
  423. * @return array properties corresponding to the options for the action
  424. */
  425. public function getOptionValues($actionID)
  426. {
  427. // $actionId might be used in subclasses to provide properties specific to action id
  428. $properties = [];
  429. foreach ($this->options($this->action->id) as $property) {
  430. $properties[$property] = $this->$property;
  431. }
  432. return $properties;
  433. }
  434. /**
  435. * Returns the names of valid options passed during execution.
  436. *
  437. * @return array the names of the options passed during execution
  438. */
  439. public function getPassedOptions()
  440. {
  441. return $this->_passedOptions;
  442. }
  443. /**
  444. * Returns the properties corresponding to the passed options.
  445. *
  446. * @return array the properties corresponding to the passed options
  447. */
  448. public function getPassedOptionValues()
  449. {
  450. $properties = [];
  451. foreach ($this->_passedOptions as $property) {
  452. $properties[$property] = $this->$property;
  453. }
  454. return $properties;
  455. }
  456. /**
  457. * Returns one-line short summary describing this controller.
  458. *
  459. * You may override this method to return customized summary.
  460. * The default implementation returns first line from the PHPDoc comment.
  461. *
  462. * @return string
  463. */
  464. public function getHelpSummary()
  465. {
  466. return $this->parseDocCommentSummary(new \ReflectionClass($this));
  467. }
  468. /**
  469. * Returns help information for this controller.
  470. *
  471. * You may override this method to return customized help.
  472. * The default implementation returns help information retrieved from the PHPDoc comment.
  473. * @return string
  474. */
  475. public function getHelp()
  476. {
  477. return $this->parseDocCommentDetail(new \ReflectionClass($this));
  478. }
  479. /**
  480. * Returns a one-line short summary describing the specified action.
  481. * @param Action $action action to get summary for
  482. * @return string a one-line short summary describing the specified action.
  483. */
  484. public function getActionHelpSummary($action)
  485. {
  486. if ($action === null) {
  487. return $this->ansiFormat(Yii::t('yii', 'Action not found.'), Console::FG_RED);
  488. }
  489. return $this->parseDocCommentSummary($this->getActionMethodReflection($action));
  490. }
  491. /**
  492. * Returns the detailed help information for the specified action.
  493. * @param Action $action action to get help for
  494. * @return string the detailed help information for the specified action.
  495. */
  496. public function getActionHelp($action)
  497. {
  498. return $this->parseDocCommentDetail($this->getActionMethodReflection($action));
  499. }
  500. /**
  501. * Returns the help information for the anonymous arguments for the action.
  502. *
  503. * The returned value should be an array. The keys are the argument names, and the values are
  504. * the corresponding help information. Each value must be an array of the following structure:
  505. *
  506. * - required: bool, whether this argument is required
  507. * - type: string|null, the PHP type(s) of this argument
  508. * - default: mixed, the default value of this argument
  509. * - comment: string, the description of this argument
  510. *
  511. * The default implementation will return the help information extracted from the Reflection or
  512. * DocBlock of the parameters corresponding to the action method.
  513. *
  514. * @param Action $action the action instance
  515. * @return array the help information of the action arguments
  516. */
  517. public function getActionArgsHelp($action)
  518. {
  519. $method = $this->getActionMethodReflection($action);
  520. $tags = $this->parseDocCommentTags($method);
  521. $tags['param'] = isset($tags['param']) ? (array) $tags['param'] : [];
  522. $phpDocParams = [];
  523. foreach ($tags['param'] as $i => $tag) {
  524. if (preg_match('/^(?<type>\S+)(\s+\$(?<name>\w+))?(?<comment>.*)/us', $tag, $matches) === 1) {
  525. $key = empty($matches['name']) ? $i : $matches['name'];
  526. $phpDocParams[$key] = ['type' => $matches['type'], 'comment' => $matches['comment']];
  527. }
  528. }
  529. unset($tags);
  530. $args = [];
  531. /** @var \ReflectionParameter $parameter */
  532. foreach ($method->getParameters() as $i => $parameter) {
  533. $type = null;
  534. $comment = '';
  535. if (PHP_MAJOR_VERSION > 5 && $parameter->hasType()) {
  536. $reflectionType = $parameter->getType();
  537. if (PHP_VERSION_ID >= 70100) {
  538. $types = method_exists($reflectionType, 'getTypes') ? $reflectionType->getTypes() : [$reflectionType];
  539. foreach ($types as $key => $reflectionType) {
  540. $types[$key] = $reflectionType->getName();
  541. }
  542. $type = implode('|', $types);
  543. } else {
  544. $type = (string) $reflectionType;
  545. }
  546. }
  547. // find PhpDoc tag by property name or position
  548. $key = isset($phpDocParams[$parameter->name]) ? $parameter->name : (isset($phpDocParams[$i]) ? $i : null);
  549. if ($key !== null) {
  550. $comment = $phpDocParams[$key]['comment'];
  551. if ($type === null && !empty($phpDocParams[$key]['type'])) {
  552. $type = $phpDocParams[$key]['type'];
  553. }
  554. }
  555. // if type still not detected, then using type of default value
  556. if ($type === null && $parameter->isDefaultValueAvailable() && $parameter->getDefaultValue() !== null) {
  557. $type = gettype($parameter->getDefaultValue());
  558. }
  559. $args[$parameter->name] = [
  560. 'required' => !$parameter->isOptional(),
  561. 'type' => $type,
  562. 'default' => $parameter->isDefaultValueAvailable() ? $parameter->getDefaultValue() : null,
  563. 'comment' => $comment,
  564. ];
  565. }
  566. return $args;
  567. }
  568. /**
  569. * Returns the help information for the options for the action.
  570. *
  571. * The returned value should be an array. The keys are the option names, and the values are
  572. * the corresponding help information. Each value must be an array of the following structure:
  573. *
  574. * - type: string, the PHP type of this argument.
  575. * - default: string, the default value of this argument
  576. * - comment: string, the comment of this argument
  577. *
  578. * The default implementation will return the help information extracted from the doc-comment of
  579. * the properties corresponding to the action options.
  580. *
  581. * @param Action $action
  582. * @return array the help information of the action options
  583. */
  584. public function getActionOptionsHelp($action)
  585. {
  586. $optionNames = $this->options($action->id);
  587. if (empty($optionNames)) {
  588. return [];
  589. }
  590. $class = new \ReflectionClass($this);
  591. $options = [];
  592. foreach ($class->getProperties() as $property) {
  593. $name = $property->getName();
  594. if (!in_array($name, $optionNames, true)) {
  595. continue;
  596. }
  597. $defaultValue = $property->getValue($this);
  598. $tags = $this->parseDocCommentTags($property);
  599. // Display camelCase options in kebab-case
  600. $name = Inflector::camel2id($name, '-', true);
  601. if (isset($tags['var']) || isset($tags['property'])) {
  602. $doc = isset($tags['var']) ? $tags['var'] : $tags['property'];
  603. if (is_array($doc)) {
  604. $doc = reset($doc);
  605. }
  606. if (preg_match('/^(\S+)(.*)/s', $doc, $matches)) {
  607. $type = $matches[1];
  608. $comment = $matches[2];
  609. } else {
  610. $type = null;
  611. $comment = $doc;
  612. }
  613. $options[$name] = [
  614. 'type' => $type,
  615. 'default' => $defaultValue,
  616. 'comment' => $comment,
  617. ];
  618. } else {
  619. $options[$name] = [
  620. 'type' => null,
  621. 'default' => $defaultValue,
  622. 'comment' => '',
  623. ];
  624. }
  625. }
  626. return $options;
  627. }
  628. private $_reflections = [];
  629. /**
  630. * @param Action $action
  631. * @return \ReflectionFunctionAbstract
  632. */
  633. protected function getActionMethodReflection($action)
  634. {
  635. if (!isset($this->_reflections[$action->id])) {
  636. if ($action instanceof InlineAction) {
  637. $this->_reflections[$action->id] = new \ReflectionMethod($this, $action->actionMethod);
  638. } else {
  639. $this->_reflections[$action->id] = new \ReflectionMethod($action, 'run');
  640. }
  641. }
  642. return $this->_reflections[$action->id];
  643. }
  644. /**
  645. * Parses the comment block into tags.
  646. * @param \ReflectionClass|\ReflectionProperty|\ReflectionFunctionAbstract $reflection the comment block
  647. * @return array the parsed tags
  648. */
  649. protected function parseDocCommentTags($reflection)
  650. {
  651. $comment = $reflection->getDocComment();
  652. $comment = "@description \n" . strtr(trim(preg_replace('/^\s*\**([ \t])?/m', '', trim($comment, '/'))), "\r", '');
  653. $parts = preg_split('/^\s*@/m', $comment, -1, PREG_SPLIT_NO_EMPTY);
  654. $tags = [];
  655. foreach ($parts as $part) {
  656. if (preg_match('/^(\w+)(.*)/ms', trim($part), $matches)) {
  657. $name = $matches[1];
  658. if (!isset($tags[$name])) {
  659. $tags[$name] = trim($matches[2]);
  660. } elseif (is_array($tags[$name])) {
  661. $tags[$name][] = trim($matches[2]);
  662. } else {
  663. $tags[$name] = [$tags[$name], trim($matches[2])];
  664. }
  665. }
  666. }
  667. return $tags;
  668. }
  669. /**
  670. * Returns the first line of docblock.
  671. *
  672. * @param \ReflectionClass|\ReflectionProperty|\ReflectionFunctionAbstract $reflection
  673. * @return string
  674. */
  675. protected function parseDocCommentSummary($reflection)
  676. {
  677. $docLines = preg_split('~\R~u', $reflection->getDocComment());
  678. if (isset($docLines[1])) {
  679. return trim($docLines[1], "\t *");
  680. }
  681. return '';
  682. }
  683. /**
  684. * Returns full description from the docblock.
  685. *
  686. * @param \ReflectionClass|\ReflectionProperty|\ReflectionFunctionAbstract $reflection
  687. * @return string
  688. */
  689. protected function parseDocCommentDetail($reflection)
  690. {
  691. $comment = strtr(trim(preg_replace('/^\s*\**([ \t])?/m', '', trim($reflection->getDocComment(), '/'))), "\r", '');
  692. if (preg_match('/^\s*@\w+/m', $comment, $matches, PREG_OFFSET_CAPTURE)) {
  693. $comment = trim(substr($comment, 0, $matches[0][1]));
  694. }
  695. if ($comment !== '') {
  696. return rtrim(Console::renderColoredString(Console::markdownToAnsi($comment)));
  697. }
  698. return '';
  699. }
  700. }