ReStructuredTextDescriptor.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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\Helper\Helper;
  14. use Symfony\Component\Console\Input\InputArgument;
  15. use Symfony\Component\Console\Input\InputDefinition;
  16. use Symfony\Component\Console\Input\InputOption;
  17. use Symfony\Component\Console\Output\OutputInterface;
  18. use Symfony\Component\String\UnicodeString;
  19. class ReStructuredTextDescriptor extends Descriptor
  20. {
  21. // <h1>
  22. private string $partChar = '=';
  23. // <h2>
  24. private string $chapterChar = '-';
  25. // <h3>
  26. private string $sectionChar = '~';
  27. // <h4>
  28. private string $subsectionChar = '.';
  29. // <h5>
  30. private string $subsubsectionChar = '^';
  31. // <h6>
  32. private string $paragraphsChar = '"';
  33. private array $visibleNamespaces = [];
  34. public function describe(OutputInterface $output, object $object, array $options = []): void
  35. {
  36. $decorated = $output->isDecorated();
  37. $output->setDecorated(false);
  38. parent::describe($output, $object, $options);
  39. $output->setDecorated($decorated);
  40. }
  41. /**
  42. * Override parent method to set $decorated = true.
  43. */
  44. protected function write(string $content, bool $decorated = true): void
  45. {
  46. parent::write($content, $decorated);
  47. }
  48. protected function describeInputArgument(InputArgument $argument, array $options = []): void
  49. {
  50. $this->write(
  51. $argument->getName() ?: '<none>'."\n".str_repeat($this->paragraphsChar, Helper::width($argument->getName()))."\n\n"
  52. .($argument->getDescription() ? preg_replace('/\s*[\r\n]\s*/', "\n", $argument->getDescription())."\n\n" : '')
  53. .'- **Is required**: '.($argument->isRequired() ? 'yes' : 'no')."\n"
  54. .'- **Is array**: '.($argument->isArray() ? 'yes' : 'no')."\n"
  55. .'- **Default**: ``'.str_replace("\n", '', var_export($argument->getDefault(), true)).'``'
  56. );
  57. }
  58. protected function describeInputOption(InputOption $option, array $options = []): void
  59. {
  60. $name = '\-\-'.$option->getName();
  61. if ($option->isNegatable()) {
  62. $name .= '|\-\-no-'.$option->getName();
  63. }
  64. if ($option->getShortcut()) {
  65. $name .= '|-'.str_replace('|', '|-', $option->getShortcut());
  66. }
  67. $optionDescription = $option->getDescription() ? preg_replace('/\s*[\r\n]\s*/', "\n\n", $option->getDescription())."\n\n" : '';
  68. $optionDescription = (new UnicodeString($optionDescription))->ascii();
  69. $this->write(
  70. $name."\n".str_repeat($this->paragraphsChar, Helper::width($name))."\n\n"
  71. .$optionDescription
  72. .'- **Accept value**: '.($option->acceptValue() ? 'yes' : 'no')."\n"
  73. .'- **Is value required**: '.($option->isValueRequired() ? 'yes' : 'no')."\n"
  74. .'- **Is multiple**: '.($option->isArray() ? 'yes' : 'no')."\n"
  75. .'- **Is negatable**: '.($option->isNegatable() ? 'yes' : 'no')."\n"
  76. .'- **Default**: ``'.str_replace("\n", '', var_export($option->getDefault(), true)).'``'."\n"
  77. );
  78. }
  79. protected function describeInputDefinition(InputDefinition $definition, array $options = []): void
  80. {
  81. if ($showArguments = ((bool) $definition->getArguments())) {
  82. $this->write("Arguments\n".str_repeat($this->subsubsectionChar, 9))."\n\n";
  83. foreach ($definition->getArguments() as $argument) {
  84. $this->write("\n\n");
  85. $this->describeInputArgument($argument);
  86. }
  87. }
  88. if ($nonDefaultOptions = $this->getNonDefaultOptions($definition)) {
  89. if ($showArguments) {
  90. $this->write("\n\n");
  91. }
  92. $this->write("Options\n".str_repeat($this->subsubsectionChar, 7)."\n\n");
  93. foreach ($nonDefaultOptions as $option) {
  94. $this->describeInputOption($option);
  95. $this->write("\n");
  96. }
  97. }
  98. }
  99. protected function describeCommand(Command $command, array $options = []): void
  100. {
  101. if ($options['short'] ?? false) {
  102. $this->write(
  103. '``'.$command->getName()."``\n"
  104. .str_repeat($this->subsectionChar, Helper::width($command->getName()))."\n\n"
  105. .($command->getDescription() ? $command->getDescription()."\n\n" : '')
  106. ."Usage\n".str_repeat($this->paragraphsChar, 5)."\n\n"
  107. .array_reduce($command->getAliases(), static fn ($carry, $usage) => $carry.'- ``'.$usage.'``'."\n")
  108. );
  109. return;
  110. }
  111. $command->mergeApplicationDefinition(false);
  112. foreach ($command->getAliases() as $alias) {
  113. $this->write('.. _'.$alias.":\n\n");
  114. }
  115. $this->write(
  116. $command->getName()."\n"
  117. .str_repeat($this->subsectionChar, Helper::width($command->getName()))."\n\n"
  118. .($command->getDescription() ? $command->getDescription()."\n\n" : '')
  119. ."Usage\n".str_repeat($this->subsubsectionChar, 5)."\n\n"
  120. .array_reduce(array_merge([$command->getSynopsis()], $command->getAliases(), $command->getUsages()), static fn ($carry, $usage) => $carry.'- ``'.$usage.'``'."\n")
  121. );
  122. if ($help = $command->getProcessedHelp()) {
  123. $this->write("\n");
  124. $this->write($help);
  125. }
  126. $definition = $command->getDefinition();
  127. if ($definition->getOptions() || $definition->getArguments()) {
  128. $this->write("\n\n");
  129. $this->describeInputDefinition($definition);
  130. }
  131. }
  132. protected function describeApplication(Application $application, array $options = []): void
  133. {
  134. $description = new ApplicationDescription($application, $options['namespace'] ?? null);
  135. $title = $this->getApplicationTitle($application);
  136. $this->write($title."\n".str_repeat($this->partChar, Helper::width($title)));
  137. $this->createTableOfContents($description, $application);
  138. $this->describeCommands($application, $options);
  139. }
  140. private function getApplicationTitle(Application $application): string
  141. {
  142. if ('UNKNOWN' === $application->getName()) {
  143. return 'Console Tool';
  144. }
  145. if ('UNKNOWN' !== $application->getVersion()) {
  146. return sprintf('%s %s', $application->getName(), $application->getVersion());
  147. }
  148. return $application->getName();
  149. }
  150. private function describeCommands($application, array $options): void
  151. {
  152. $title = 'Commands';
  153. $this->write("\n\n$title\n".str_repeat($this->chapterChar, Helper::width($title))."\n\n");
  154. foreach ($this->visibleNamespaces as $namespace) {
  155. if ('_global' === $namespace) {
  156. $commands = $application->all('');
  157. $this->write('Global'."\n".str_repeat($this->sectionChar, Helper::width('Global'))."\n\n");
  158. } else {
  159. $commands = $application->all($namespace);
  160. $this->write($namespace."\n".str_repeat($this->sectionChar, Helper::width($namespace))."\n\n");
  161. }
  162. foreach ($this->removeAliasesAndHiddenCommands($commands) as $command) {
  163. $this->describeCommand($command, $options);
  164. $this->write("\n\n");
  165. }
  166. }
  167. }
  168. private function createTableOfContents(ApplicationDescription $description, Application $application): void
  169. {
  170. $this->setVisibleNamespaces($description);
  171. $chapterTitle = 'Table of Contents';
  172. $this->write("\n\n$chapterTitle\n".str_repeat($this->chapterChar, Helper::width($chapterTitle))."\n\n");
  173. foreach ($this->visibleNamespaces as $namespace) {
  174. if ('_global' === $namespace) {
  175. $commands = $application->all('');
  176. } else {
  177. $commands = $application->all($namespace);
  178. $this->write("\n\n");
  179. $this->write($namespace."\n".str_repeat($this->sectionChar, Helper::width($namespace))."\n\n");
  180. }
  181. $commands = $this->removeAliasesAndHiddenCommands($commands);
  182. $this->write("\n\n");
  183. $this->write(implode("\n", array_map(static fn ($commandName) => sprintf('- `%s`_', $commandName), array_keys($commands))));
  184. }
  185. }
  186. private function getNonDefaultOptions(InputDefinition $definition): array
  187. {
  188. $globalOptions = [
  189. 'help',
  190. 'quiet',
  191. 'verbose',
  192. 'version',
  193. 'ansi',
  194. 'no-interaction',
  195. ];
  196. $nonDefaultOptions = [];
  197. foreach ($definition->getOptions() as $option) {
  198. // Skip global options.
  199. if (!\in_array($option->getName(), $globalOptions)) {
  200. $nonDefaultOptions[] = $option;
  201. }
  202. }
  203. return $nonDefaultOptions;
  204. }
  205. private function setVisibleNamespaces(ApplicationDescription $description): void
  206. {
  207. $commands = $description->getCommands();
  208. foreach ($description->getNamespaces() as $namespace) {
  209. try {
  210. $namespaceCommands = $namespace['commands'];
  211. foreach ($namespaceCommands as $key => $commandName) {
  212. if (!\array_key_exists($commandName, $commands)) {
  213. // If the array key does not exist, then this is an alias.
  214. unset($namespaceCommands[$key]);
  215. } elseif ($commands[$commandName]->isHidden()) {
  216. unset($namespaceCommands[$key]);
  217. }
  218. }
  219. if (!$namespaceCommands) {
  220. // If the namespace contained only aliases or hidden commands, skip the namespace.
  221. continue;
  222. }
  223. } catch (\Exception) {
  224. }
  225. $this->visibleNamespaces[] = $namespace['id'];
  226. }
  227. }
  228. private function removeAliasesAndHiddenCommands(array $commands): array
  229. {
  230. foreach ($commands as $key => $command) {
  231. if ($command->isHidden() || \in_array($key, $command->getAliases(), true)) {
  232. unset($commands[$key]);
  233. }
  234. }
  235. unset($commands['completion']);
  236. return $commands;
  237. }
  238. }