Completed
Pull Request — master (#21)
by Greg
03:15
created

XmlFormatter::validate()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 2
Metric Value
c 2
b 0
f 2
dl 0
loc 17
rs 9.2
cc 4
eloc 11
nc 4
nop 1
1
<?php
2
namespace Consolidation\OutputFormatters\Formatters;
3
4
use Symfony\Component\Console\Output\OutputInterface;
5
use Symfony\Component\Console\Helper\Table;
6
use Symfony\Component\Console\Helper\TableStyle;
7
8
use Consolidation\OutputFormatters\FormatterInterface;
9
use Consolidation\OutputFormatters\ValidationInterface;
10
use Consolidation\OutputFormatters\FormatterOptions;
11
use Consolidation\OutputFormatters\StructuredData\TableDataInterface;
12
use Consolidation\OutputFormatters\Transformations\ReorderFields;
13
use Consolidation\OutputFormatters\Exception\IncompatibleDataException;
14
use Consolidation\OutputFormatters\StructuredData\Xml\DomDataInterface;
15
16
/**
17
 * Display a table of data with the Symfony Table class.
18
 *
19
 * This formatter takes data of either the RowsOfFields or
20
 * AssociativeList data type.  Tables can be rendered with the
21
 * rows running either vertically (the normal orientation) or
22
 * horizontally.  By default, associative lists will be displayed
23
 * as two columns, with the key in the first column and the
24
 * value in the second column.
25
 */
26
class XmlFormatter implements FormatterInterface, ValidationInterface
27
{
28
    public function __construct()
29
    {
30
    }
31
32
    public function validDataTypes()
33
    {
34
        return
35
            [
36
                new \ReflectionClass('\DOMDocument'),
37
                new \ReflectionClass('\ArrayObject'),
38
            ];
39
    }
40
41
    /**
42
     * @inheritdoc
43
     */
44
    public function validate($structuredData)
45
    {
46
        if ($structuredData instanceof \DOMDocument) {
47
            return $structuredData;
48
        }
49
        if ($structuredData instanceof DomDataInterface) {
50
            return $structuredData->getDomData();
51
        }
52
        if (!is_array($structuredData)) {
53
            throw new IncompatibleDataException(
54
                $this,
55
                $structuredData,
56
                $this->validDataTypes()
57
            );
58
        }
59
        return $structuredData;
60
    }
61
62
    /**
63
     * @inheritdoc
64
     */
65
    public function write(OutputInterface $output, $dom, FormatterOptions $options)
66
    {
67
        if (is_array($dom)) {
68
            $schema = $options->getXmlSchema();
69
            $dom = $schema->arrayToXML($dom);
70
        }
71
        $dom->formatOutput = true;
72
        $output->writeln($dom->saveXML());
73
    }
74
}
75