HelpCommand.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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\Command;
  11. use Symfony\Component\Console\Descriptor\ApplicationDescription;
  12. use Symfony\Component\Console\Helper\DescriptorHelper;
  13. use Symfony\Component\Console\Input\InputArgument;
  14. use Symfony\Component\Console\Input\InputInterface;
  15. use Symfony\Component\Console\Input\InputOption;
  16. use Symfony\Component\Console\Output\OutputInterface;
  17. /**
  18. * HelpCommand displays the help for a given command.
  19. *
  20. * @author Fabien Potencier <fabien@symfony.com>
  21. */
  22. class HelpCommand extends Command
  23. {
  24. private Command $command;
  25. protected function configure(): void
  26. {
  27. $this->ignoreValidationErrors();
  28. $this
  29. ->setName('help')
  30. ->setDefinition([
  31. new InputArgument('command_name', InputArgument::OPTIONAL, 'The command name', 'help', fn () => array_keys((new ApplicationDescription($this->getApplication()))->getCommands())),
  32. new InputOption('format', null, InputOption::VALUE_REQUIRED, 'The output format (txt, xml, json, or md)', 'txt', fn () => (new DescriptorHelper())->getFormats()),
  33. new InputOption('raw', null, InputOption::VALUE_NONE, 'To output raw command help'),
  34. ])
  35. ->setDescription('Display help for a command')
  36. ->setHelp(<<<'EOF'
  37. The <info>%command.name%</info> command displays help for a given command:
  38. <info>%command.full_name% list</info>
  39. You can also output the help in other formats by using the <comment>--format</comment> option:
  40. <info>%command.full_name% --format=xml list</info>
  41. To display the list of available commands, please use the <info>list</info> command.
  42. EOF
  43. )
  44. ;
  45. }
  46. public function setCommand(Command $command): void
  47. {
  48. $this->command = $command;
  49. }
  50. protected function execute(InputInterface $input, OutputInterface $output): int
  51. {
  52. $this->command ??= $this->getApplication()->find($input->getArgument('command_name'));
  53. $helper = new DescriptorHelper();
  54. $helper->describe($output, $this->command, [
  55. 'format' => $input->getOption('format'),
  56. 'raw_text' => $input->getOption('raw'),
  57. ]);
  58. unset($this->command);
  59. return 0;
  60. }
  61. }