DescriptorHelper.php 2.4 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\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. * @param object $object
  46. *
  47. * @throws InvalidArgumentException when the given format is not supported
  48. */
  49. public function describe(OutputInterface $output, $object, array $options = [])
  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. * @param string $format
  65. *
  66. * @return $this
  67. */
  68. public function register($format, DescriptorInterface $descriptor)
  69. {
  70. $this->descriptors[$format] = $descriptor;
  71. return $this;
  72. }
  73. /**
  74. * {@inheritdoc}
  75. */
  76. public function getName()
  77. {
  78. return 'descriptor';
  79. }
  80. }