DescriptorHelper.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. * @throws InvalidArgumentException when the given format is not supported
  48. */
  49. public function describe(OutputInterface $output, ?object $object, array $options = []): void
  50. {
  51. $options = array_merge([
  52. 'raw_text' => false,
  53. 'format' => 'txt',
  54. ], $options);
  55. if (!isset($this->descriptors[$options['format']])) {
  56. throw new InvalidArgumentException(\sprintf('Unsupported format "%s".', $options['format']));
  57. }
  58. $descriptor = $this->descriptors[$options['format']];
  59. $descriptor->describe($output, $object, $options);
  60. }
  61. /**
  62. * Registers a descriptor.
  63. *
  64. * @return $this
  65. */
  66. public function register(string $format, DescriptorInterface $descriptor): static
  67. {
  68. $this->descriptors[$format] = $descriptor;
  69. return $this;
  70. }
  71. public function getName(): string
  72. {
  73. return 'descriptor';
  74. }
  75. public function getFormats(): array
  76. {
  77. return array_keys($this->descriptors);
  78. }
  79. }