DescriptorHelper.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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\Helper;
  11. use Symfony\Component\Console\Descriptor\DescriptorInterface;
  12. use Symfony\Component\Console\Descriptor\JsonDescriptor;
  13. use Symfony\Component\Console\Descriptor\MarkdownDescriptor;
  14. use Symfony\Component\Console\Descriptor\ReStructuredTextDescriptor;
  15. use Symfony\Component\Console\Descriptor\TextDescriptor;
  16. use Symfony\Component\Console\Descriptor\XmlDescriptor;
  17. use Symfony\Component\Console\Exception\InvalidArgumentException;
  18. use Symfony\Component\Console\Output\OutputInterface;
  19. /**
  20. * This class adds helper method to describe objects in various formats.
  21. *
  22. * @author Jean-François Simon <contact@jfsimon.fr>
  23. */
  24. class DescriptorHelper extends Helper
  25. {
  26. /**
  27. * @var DescriptorInterface[]
  28. */
  29. private array $descriptors = [];
  30. public function __construct()
  31. {
  32. $this
  33. ->register('txt', new TextDescriptor())
  34. ->register('xml', new XmlDescriptor())
  35. ->register('json', new JsonDescriptor())
  36. ->register('md', new MarkdownDescriptor())
  37. ->register('rst', new ReStructuredTextDescriptor())
  38. ;
  39. }
  40. /**
  41. * Describes an object if supported.
  42. *
  43. * Available options are:
  44. * * format: string, the output format name
  45. * * raw_text: boolean, sets output type as raw
  46. *
  47. * @return void
  48. *
  49. * @throws InvalidArgumentException when the given format is not supported
  50. */
  51. public function describe(OutputInterface $output, ?object $object, array $options = [])
  52. {
  53. $options = array_merge([
  54. 'raw_text' => false,
  55. 'format' => 'txt',
  56. ], $options);
  57. if (!isset($this->descriptors[$options['format']])) {
  58. throw new InvalidArgumentException(sprintf('Unsupported format "%s".', $options['format']));
  59. }
  60. $descriptor = $this->descriptors[$options['format']];
  61. $descriptor->describe($output, $object, $options);
  62. }
  63. /**
  64. * Registers a descriptor.
  65. *
  66. * @return $this
  67. */
  68. public function register(string $format, DescriptorInterface $descriptor): static
  69. {
  70. $this->descriptors[$format] = $descriptor;
  71. return $this;
  72. }
  73. public function getName(): string
  74. {
  75. return 'descriptor';
  76. }
  77. public function getFormats(): array
  78. {
  79. return array_keys($this->descriptors);
  80. }
  81. }