| 1 |
<?php |
| 2 |
|
| 3 |
/* |
| 4 |
* This file is part of the Symfony package. |
| 5 |
* |
| 6 |
* (c) Fabien Potencier <fabien@symfony.com> |
| 7 |
* |
| 8 |
* For the full copyright and license information, please view the LICENSE |
| 9 |
* file that was distributed with this source code. |
| 10 |
*/ |
| 11 |
|
| 12 |
namespace Symfony\Component\Console\Helper; |
| 13 |
|
| 14 |
use Symfony\Component\Console\Descriptor\DescriptorInterface; |
| 15 |
use Symfony\Component\Console\Descriptor\JsonDescriptor; |
| 16 |
use Symfony\Component\Console\Descriptor\MarkdownDescriptor; |
| 17 |
use Symfony\Component\Console\Descriptor\TextDescriptor; |
| 18 |
use Symfony\Component\Console\Descriptor\XmlDescriptor; |
| 19 |
use Symfony\Component\Console\Exception\InvalidArgumentException; |
| 20 |
use Symfony\Component\Console\Output\OutputInterface; |
| 21 |
|
| 22 |
/** |
| 23 |
* This class adds helper method to describe objects in various formats. |
| 24 |
* |
| 25 |
* @author Jean-François Simon <contact@jfsimon.fr> |
| 26 |
*/ |
| 27 |
class DescriptorHelper extends Helper |
| 28 |
{ |
| 29 |
/** |
| 30 |
* @var DescriptorInterface[] |
| 31 |
*/ |
| 32 |
private $descriptors = []; |
| 33 |
|
| 34 |
public function __construct() |
| 35 |
{ |
| 36 |
$this |
| 37 |
->register('txt', new TextDescriptor()) |
| 38 |
->register('xml', new XmlDescriptor()) |
| 39 |
->register('json', new JsonDescriptor()) |
| 40 |
->register('md', new MarkdownDescriptor()) |
| 41 |
; |
| 42 |
} |
| 43 |
|
| 44 |
/** |
| 45 |
* Describes an object if supported. |
| 46 |
* |
| 47 |
* Available options are: |
| 48 |
* * format: string, the output format name |
| 49 |
* * raw_text: boolean, sets output type as raw |
| 50 |
* |
| 51 |
* @param object $object |
| 52 |
* |
| 53 |
* @throws InvalidArgumentException when the given format is not supported |
| 54 |
*/ |
| 55 |
public function describe(OutputInterface $output, $object, array $options = []) |
| 56 |
{ |
| 57 |
$options = array_merge([ |
| 58 |
'raw_text' => false, |
| 59 |
'format' => 'txt', |
| 60 |
], $options); |
| 61 |
|
| 62 |
if (!isset($this->descriptors[$options['format']])) { |
| 63 |
throw new InvalidArgumentException(sprintf('Unsupported format "%s".', $options['format'])); |
| 64 |
} |
| 65 |
|
| 66 |
$descriptor = $this->descriptors[$options['format']]; |
| 67 |
$descriptor->describe($output, $object, $options); |
| 68 |
} |
| 69 |
|
| 70 |
/** |
| 71 |
* Registers a descriptor. |
| 72 |
* |
| 73 |
* @param string $format |
| 74 |
* |
| 75 |
* @return $this |
| 76 |
*/ |
| 77 |
public function register($format, DescriptorInterface $descriptor) |
| 78 |
{ |
| 79 |
$this->descriptors[$format] = $descriptor; |
| 80 |
|
| 81 |
return $this; |
| 82 |
} |
| 83 |
|
| 84 |
/** |
| 85 |
* {@inheritdoc} |
| 86 |
*/ |
| 87 |
public function getName() |
| 88 |
{ |
| 89 |
return 'descriptor'; |
| 90 |
} |
| 91 |
} |
| 92 |
|