DescriptorHelper.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. * @param OutputInterface $output
  44. * @param object $object
  45. * @param string $format
  46. * @param boolean $raw
  47. */
  48. public function describe(OutputInterface $output, $object, $format = null, $raw = false, $namespace = null)
  49. {
  50. $options = array('raw_text' => $raw, 'format' => $format ?: 'txt', 'namespace' => $namespace);
  51. $type = !$raw && 'txt' === $options['format'] ? OutputInterface::OUTPUT_NORMAL : OutputInterface::OUTPUT_RAW;
  52. if (!isset($this->descriptors[$options['format']])) {
  53. throw new \InvalidArgumentException(sprintf('Unsupported format "%s".', $options['format']));
  54. }
  55. $descriptor = $this->descriptors[$options['format']];
  56. $output->writeln($descriptor->describe($object, $options), $type);
  57. }
  58. /**
  59. * Registers a descriptor.
  60. *
  61. * @param string $format
  62. * @param DescriptorInterface $descriptor
  63. *
  64. * @return DescriptorHelper
  65. */
  66. public function register($format, DescriptorInterface $descriptor)
  67. {
  68. $this->descriptors[$format] = $descriptor;
  69. return $this;
  70. }
  71. /**
  72. * {@inheritdoc}
  73. */
  74. public function getName()
  75. {
  76. return 'descriptor';
  77. }
  78. }