DescriptorHelper.php 2.5 KB

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