1 | <?php |
||
9 | final class XmlTransformer implements TransformerInterface |
||
10 | { |
||
11 | /** |
||
12 | * @var bool |
||
13 | */ |
||
14 | private $formatOutput; |
||
15 | |||
16 | /** |
||
17 | * @var int |
||
18 | */ |
||
19 | private $options; |
||
20 | |||
21 | /** |
||
22 | * @param bool $formatOutput |
||
23 | * @param int $options |
||
24 | */ |
||
25 | 1 | public function __construct(bool $formatOutput = false, int $options = LIBXML_NOEMPTYTAG) |
|
30 | |||
31 | /** |
||
32 | * @param array $data |
||
33 | * |
||
34 | * @return string |
||
35 | */ |
||
36 | 1 | public function transform(array $data): string |
|
45 | |||
46 | /** |
||
47 | * @param \DOMDocument $document |
||
48 | * @param \DOMNode $listNode |
||
49 | * @param array $data |
||
50 | */ |
||
51 | 1 | private function dataToNodes(\DOMDocument $document, \DOMNode $listNode, array $data) |
|
52 | { |
||
53 | 1 | foreach ($data as $key => $value) { |
|
54 | 1 | if (is_array($value)) { |
|
55 | 1 | $childNode = $document->createElement(is_int($key) ? Inflector::singularize($listNode->nodeName) : $key); |
|
56 | 1 | $this->dataToNodes($document, $childNode, $value); |
|
57 | } else { |
||
58 | 1 | if (is_string($value)) { |
|
59 | 1 | if (strpos($value, '<') !== false || strpos($value, '&') !== false) { |
|
60 | 1 | $childNode = $document->createElement($key); |
|
61 | 1 | $childNode->appendChild($document->createCDATASection($value)); |
|
62 | } else { |
||
63 | 1 | $childNode = $document->createElement($key, $value); |
|
64 | } |
||
65 | 1 | $childNode->setAttribute('type', 'string'); |
|
66 | 1 | } elseif (null === $value) { |
|
67 | 1 | $childNode = $document->createElement($key); |
|
68 | } else { |
||
69 | 1 | $childNode = $document->createElement($key, $this->getValueAsString($value)); |
|
70 | 1 | $childNode->setAttribute('type', $this->getType($value)); |
|
71 | } |
||
72 | } |
||
73 | |||
74 | 1 | $listNode->appendChild($childNode); |
|
75 | } |
||
76 | 1 | } |
|
77 | |||
78 | /** |
||
79 | * @param bool|float|int $value |
||
80 | * |
||
81 | * @return string|null |
||
82 | * |
||
83 | * @throws \InvalidArgumentException |
||
84 | */ |
||
85 | 1 | private function getValueAsString($value): string |
|
97 | |||
98 | /** |
||
99 | * @param bool|float|int|string $value |
||
100 | * |
||
101 | * @return null|string |
||
102 | */ |
||
103 | 1 | private function getType($value): string |
|
123 | } |
||
124 |