PageRenderTime 44ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/laradock/vendor/symfony/console/Descriptor/TextDescriptor.php

https://gitlab.com/hoangduys4k5/laravelproject
PHP | 339 lines | 240 code | 49 blank | 50 comment | 41 complexity | 9e9a61780744251f81fe9f1ac7775ee0 MD5 | raw file
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Console\Descriptor;
  11. use Symfony\Component\Console\Application;
  12. use Symfony\Component\Console\Command\Command;
  13. use Symfony\Component\Console\Formatter\OutputFormatter;
  14. use Symfony\Component\Console\Helper\Helper;
  15. use Symfony\Component\Console\Input\InputArgument;
  16. use Symfony\Component\Console\Input\InputDefinition;
  17. use Symfony\Component\Console\Input\InputOption;
  18. /**
  19. * Text descriptor.
  20. *
  21. * @author Jean-François Simon <contact@jfsimon.fr>
  22. *
  23. * @internal
  24. */
  25. class TextDescriptor extends Descriptor
  26. {
  27. /**
  28. * {@inheritdoc}
  29. */
  30. protected function describeInputArgument(InputArgument $argument, array $options = [])
  31. {
  32. if (null !== $argument->getDefault() && (!\is_array($argument->getDefault()) || \count($argument->getDefault()))) {
  33. $default = sprintf('<comment> [default: %s]</comment>', $this->formatDefaultValue($argument->getDefault()));
  34. } else {
  35. $default = '';
  36. }
  37. $totalWidth = $options['total_width'] ?? Helper::width($argument->getName());
  38. $spacingWidth = $totalWidth - \strlen($argument->getName());
  39. $this->writeText(sprintf(' <info>%s</info> %s%s%s',
  40. $argument->getName(),
  41. str_repeat(' ', $spacingWidth),
  42. // + 4 = 2 spaces before <info>, 2 spaces after </info>
  43. preg_replace('/\s*[\r\n]\s*/', "\n".str_repeat(' ', $totalWidth + 4), $argument->getDescription()),
  44. $default
  45. ), $options);
  46. }
  47. /**
  48. * {@inheritdoc}
  49. */
  50. protected function describeInputOption(InputOption $option, array $options = [])
  51. {
  52. if ($option->acceptValue() && null !== $option->getDefault() && (!\is_array($option->getDefault()) || \count($option->getDefault()))) {
  53. $default = sprintf('<comment> [default: %s]</comment>', $this->formatDefaultValue($option->getDefault()));
  54. } else {
  55. $default = '';
  56. }
  57. $value = '';
  58. if ($option->acceptValue()) {
  59. $value = '='.strtoupper($option->getName());
  60. if ($option->isValueOptional()) {
  61. $value = '['.$value.']';
  62. }
  63. }
  64. $totalWidth = $options['total_width'] ?? $this->calculateTotalWidthForOptions([$option]);
  65. $synopsis = sprintf('%s%s',
  66. $option->getShortcut() ? sprintf('-%s, ', $option->getShortcut()) : ' ',
  67. sprintf($option->isNegatable() ? '--%1$s|--no-%1$s' : '--%1$s%2$s', $option->getName(), $value)
  68. );
  69. $spacingWidth = $totalWidth - Helper::width($synopsis);
  70. $this->writeText(sprintf(' <info>%s</info> %s%s%s%s',
  71. $synopsis,
  72. str_repeat(' ', $spacingWidth),
  73. // + 4 = 2 spaces before <info>, 2 spaces after </info>
  74. preg_replace('/\s*[\r\n]\s*/', "\n".str_repeat(' ', $totalWidth + 4), $option->getDescription()),
  75. $default,
  76. $option->isArray() ? '<comment> (multiple values allowed)</comment>' : ''
  77. ), $options);
  78. }
  79. /**
  80. * {@inheritdoc}
  81. */
  82. protected function describeInputDefinition(InputDefinition $definition, array $options = [])
  83. {
  84. $totalWidth = $this->calculateTotalWidthForOptions($definition->getOptions());
  85. foreach ($definition->getArguments() as $argument) {
  86. $totalWidth = max($totalWidth, Helper::width($argument->getName()));
  87. }
  88. if ($definition->getArguments()) {
  89. $this->writeText('<comment>Arguments:</comment>', $options);
  90. $this->writeText("\n");
  91. foreach ($definition->getArguments() as $argument) {
  92. $this->describeInputArgument($argument, array_merge($options, ['total_width' => $totalWidth]));
  93. $this->writeText("\n");
  94. }
  95. }
  96. if ($definition->getArguments() && $definition->getOptions()) {
  97. $this->writeText("\n");
  98. }
  99. if ($definition->getOptions()) {
  100. $laterOptions = [];
  101. $this->writeText('<comment>Options:</comment>', $options);
  102. foreach ($definition->getOptions() as $option) {
  103. if (\strlen($option->getShortcut() ?? '') > 1) {
  104. $laterOptions[] = $option;
  105. continue;
  106. }
  107. $this->writeText("\n");
  108. $this->describeInputOption($option, array_merge($options, ['total_width' => $totalWidth]));
  109. }
  110. foreach ($laterOptions as $option) {
  111. $this->writeText("\n");
  112. $this->describeInputOption($option, array_merge($options, ['total_width' => $totalWidth]));
  113. }
  114. }
  115. }
  116. /**
  117. * {@inheritdoc}
  118. */
  119. protected function describeCommand(Command $command, array $options = [])
  120. {
  121. $command->mergeApplicationDefinition(false);
  122. if ($description = $command->getDescription()) {
  123. $this->writeText('<comment>Description:</comment>', $options);
  124. $this->writeText("\n");
  125. $this->writeText(' '.$description);
  126. $this->writeText("\n\n");
  127. }
  128. $this->writeText('<comment>Usage:</comment>', $options);
  129. foreach (array_merge([$command->getSynopsis(true)], $command->getAliases(), $command->getUsages()) as $usage) {
  130. $this->writeText("\n");
  131. $this->writeText(' '.OutputFormatter::escape($usage), $options);
  132. }
  133. $this->writeText("\n");
  134. $definition = $command->getDefinition();
  135. if ($definition->getOptions() || $definition->getArguments()) {
  136. $this->writeText("\n");
  137. $this->describeInputDefinition($definition, $options);
  138. $this->writeText("\n");
  139. }
  140. $help = $command->getProcessedHelp();
  141. if ($help && $help !== $description) {
  142. $this->writeText("\n");
  143. $this->writeText('<comment>Help:</comment>', $options);
  144. $this->writeText("\n");
  145. $this->writeText(' '.str_replace("\n", "\n ", $help), $options);
  146. $this->writeText("\n");
  147. }
  148. }
  149. /**
  150. * {@inheritdoc}
  151. */
  152. protected function describeApplication(Application $application, array $options = [])
  153. {
  154. $describedNamespace = $options['namespace'] ?? null;
  155. $description = new ApplicationDescription($application, $describedNamespace);
  156. if (isset($options['raw_text']) && $options['raw_text']) {
  157. $width = $this->getColumnWidth($description->getCommands());
  158. foreach ($description->getCommands() as $command) {
  159. $this->writeText(sprintf("%-{$width}s %s", $command->getName(), $command->getDescription()), $options);
  160. $this->writeText("\n");
  161. }
  162. } else {
  163. if ('' != $help = $application->getHelp()) {
  164. $this->writeText("$help\n\n", $options);
  165. }
  166. $this->writeText("<comment>Usage:</comment>\n", $options);
  167. $this->writeText(" command [options] [arguments]\n\n", $options);
  168. $this->describeInputDefinition(new InputDefinition($application->getDefinition()->getOptions()), $options);
  169. $this->writeText("\n");
  170. $this->writeText("\n");
  171. $commands = $description->getCommands();
  172. $namespaces = $description->getNamespaces();
  173. if ($describedNamespace && $namespaces) {
  174. // make sure all alias commands are included when describing a specific namespace
  175. $describedNamespaceInfo = reset($namespaces);
  176. foreach ($describedNamespaceInfo['commands'] as $name) {
  177. $commands[$name] = $description->getCommand($name);
  178. }
  179. }
  180. // calculate max. width based on available commands per namespace
  181. $width = $this->getColumnWidth(array_merge(...array_values(array_map(function ($namespace) use ($commands) {
  182. return array_intersect($namespace['commands'], array_keys($commands));
  183. }, array_values($namespaces)))));
  184. if ($describedNamespace) {
  185. $this->writeText(sprintf('<comment>Available commands for the "%s" namespace:</comment>', $describedNamespace), $options);
  186. } else {
  187. $this->writeText('<comment>Available commands:</comment>', $options);
  188. }
  189. foreach ($namespaces as $namespace) {
  190. $namespace['commands'] = array_filter($namespace['commands'], function ($name) use ($commands) {
  191. return isset($commands[$name]);
  192. });
  193. if (!$namespace['commands']) {
  194. continue;
  195. }
  196. if (!$describedNamespace && ApplicationDescription::GLOBAL_NAMESPACE !== $namespace['id']) {
  197. $this->writeText("\n");
  198. $this->writeText(' <comment>'.$namespace['id'].'</comment>', $options);
  199. }
  200. foreach ($namespace['commands'] as $name) {
  201. $this->writeText("\n");
  202. $spacingWidth = $width - Helper::width($name);
  203. $command = $commands[$name];
  204. $commandAliases = $name === $command->getName() ? $this->getCommandAliasesText($command) : '';
  205. $this->writeText(sprintf(' <info>%s</info>%s%s', $name, str_repeat(' ', $spacingWidth), $commandAliases.$command->getDescription()), $options);
  206. }
  207. }
  208. $this->writeText("\n");
  209. }
  210. }
  211. /**
  212. * {@inheritdoc}
  213. */
  214. private function writeText(string $content, array $options = [])
  215. {
  216. $this->write(
  217. isset($options['raw_text']) && $options['raw_text'] ? strip_tags($content) : $content,
  218. isset($options['raw_output']) ? !$options['raw_output'] : true
  219. );
  220. }
  221. /**
  222. * Formats command aliases to show them in the command description.
  223. */
  224. private function getCommandAliasesText(Command $command): string
  225. {
  226. $text = '';
  227. $aliases = $command->getAliases();
  228. if ($aliases) {
  229. $text = '['.implode('|', $aliases).'] ';
  230. }
  231. return $text;
  232. }
  233. /**
  234. * Formats input option/argument default value.
  235. */
  236. private function formatDefaultValue(mixed $default): string
  237. {
  238. if (\INF === $default) {
  239. return 'INF';
  240. }
  241. if (\is_string($default)) {
  242. $default = OutputFormatter::escape($default);
  243. } elseif (\is_array($default)) {
  244. foreach ($default as $key => $value) {
  245. if (\is_string($value)) {
  246. $default[$key] = OutputFormatter::escape($value);
  247. }
  248. }
  249. }
  250. return str_replace('\\\\', '\\', json_encode($default, \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE));
  251. }
  252. /**
  253. * @param array<Command|string> $commands
  254. */
  255. private function getColumnWidth(array $commands): int
  256. {
  257. $widths = [];
  258. foreach ($commands as $command) {
  259. if ($command instanceof Command) {
  260. $widths[] = Helper::width($command->getName());
  261. foreach ($command->getAliases() as $alias) {
  262. $widths[] = Helper::width($alias);
  263. }
  264. } else {
  265. $widths[] = Helper::width($command);
  266. }
  267. }
  268. return $widths ? max($widths) + 2 : 0;
  269. }
  270. /**
  271. * @param InputOption[] $options
  272. */
  273. private function calculateTotalWidthForOptions(array $options): int
  274. {
  275. $totalWidth = 0;
  276. foreach ($options as $option) {
  277. // "-" + shortcut + ", --" + name
  278. $nameLength = 1 + max(Helper::width($option->getShortcut()), 1) + 4 + Helper::width($option->getName());
  279. if ($option->isNegatable()) {
  280. $nameLength += 6 + Helper::width($option->getName()); // |--no- + name
  281. } elseif ($option->acceptValue()) {
  282. $valueLength = 1 + Helper::width($option->getName()); // = + value
  283. $valueLength += $option->isValueOptional() ? 2 : 0; // [ + ]
  284. $nameLength += $valueLength;
  285. }
  286. $totalWidth = max($totalWidth, $nameLength);
  287. }
  288. return $totalWidth;
  289. }
  290. }