| 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 |
* @throws InvalidArgumentException when the given format is not supported |
| 52 |
*/ |
| 53 |
public function describe(OutputInterface $output, ?object $object, array $options = []) |
| 54 |
{ |
| 55 |
$options = array_merge([ |
| 56 |
'raw_text' => false, |
| 57 |
'format' => 'txt', |
| 58 |
], $options); |
| 59 |
|
| 60 |
if (!isset($this->descriptors[$options['format']])) { |
| 61 |
throw new InvalidArgumentException(sprintf('Unsupported format "%s".', $options['format'])); |
| 62 |
} |
| 63 |
|
| 64 |
$descriptor = $this->descriptors[$options['format']]; |
| 65 |
$descriptor->describe($output, $object, $options); |
| 66 |
} |
| 67 |
|
| 68 |
/** |
| 69 |
* Registers a descriptor. |
| 70 |
* |
| 71 |
* @return $this |
| 72 |
*/ |
| 73 |
public function register(string $format, DescriptorInterface $descriptor) |
| 74 |
{ |
| 75 |
$this->descriptors[$format] = $descriptor; |
| 76 |
|
| 77 |
return $this; |
| 78 |
} |
| 79 |
|
| 80 |
/** |
| 81 |
* {@inheritdoc} |
| 82 |
*/ |
| 83 |
public function getName() |
| 84 |
{ |
| 85 |
return 'descriptor'; |
| 86 |
} |
| 87 |
} |
| 88 |
|