You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
2.3 KiB

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