Controller.php 27 KB

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