DescriptorHelper.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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\Output\OutputInterface;
  17. /**
  18. * This class adds helper method to describe objects in various formats.
  19. *
  20. * @author Jean-François Simon <contact@jfsimon.fr>
  21. */
  22. class DescriptorHelper extends Helper
  23. {
  24. /**
  25. * @var DescriptorInterface[]
  26. */
  27. private $descriptors = array();
  28. /**
  29. * Constructor.
  30. */
  31. public function __construct()
  32. {
  33. $this
  34. ->register('txt', new TextDescriptor())
  35. ->register('xml', new XmlDescriptor())
  36. ->register('json', new JsonDescriptor())
  37. ->register('md', new MarkdownDescriptor())
  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. * @param OutputInterface $output
  48. * @param object $object
  49. * @param array $options
  50. *
  51. * @throws \InvalidArgumentException when the given format is not supported
  52. */
  53. public function describe(OutputInterface $output, $object, array $options = array())
  54. {
  55. $options = array_merge(array(
  56. 'raw_text' => false,
  57. 'format' => 'txt',
  58. ), $options);
  59. if (!isset($this->descriptors[$options['format']])) {
  60. throw new \InvalidArgumentException(sprintf('Unsupported format "%s".', $options['format']));
  61. }
  62. $descriptor = $this->descriptors[$options['format']];
  63. $descriptor->describe($output, $object, $options);
  64. }
  65. /**
  66. * Registers a descriptor.
  67. *
  68. * @param string $format
  69. * @param DescriptorInterface $descriptor
  70. *
  71. * @return DescriptorHelper
  72. */
  73. public function register($format, DescriptorInterface $descriptor)
  74. {
  75. $this->descriptors[$format] = $descriptor;
  76. return $this;
  77. }
  78. /**
  79. * {@inheritdoc}
  80. */
  81. public function getName()
  82. {
  83. return 'descriptor';
  84. }
  85. }