|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Chubbyphp\Serialization\Formatter; |
|
6
|
|
|
|
|
7
|
|
|
use Doctrine\Common\Inflector\Inflector; |
|
8
|
|
|
|
|
9
|
|
|
final class XmlFormatter implements FormatterInterface |
|
10
|
|
|
{ |
|
11
|
|
|
/** |
|
12
|
|
|
* @var bool |
|
13
|
|
|
*/ |
|
14
|
|
|
private $formatOutput; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* @param bool $formatOutput |
|
18
|
|
|
*/ |
|
19
|
1 |
|
public function __construct(bool $formatOutput = false) |
|
20
|
|
|
{ |
|
21
|
1 |
|
$this->formatOutput = $formatOutput; |
|
22
|
1 |
|
} |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @param array $data |
|
26
|
|
|
* |
|
27
|
|
|
* @return string |
|
28
|
|
|
*/ |
|
29
|
1 |
|
public function format(array $data): string |
|
30
|
|
|
{ |
|
31
|
1 |
|
$document = new \DOMDocument('1.0', 'UTF-8'); |
|
32
|
1 |
|
$document->formatOutput = $this->formatOutput; |
|
33
|
|
|
|
|
34
|
1 |
|
$this->dataToNodes($document, $document, $data); |
|
35
|
|
|
|
|
36
|
1 |
|
return $document->saveXML(); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* @param \DOMDocument $document |
|
41
|
|
|
* @param \DOMNode $listNode |
|
42
|
|
|
* @param array $data |
|
43
|
|
|
*/ |
|
44
|
1 |
|
private function dataToNodes(\DOMDocument $document, \DOMNode $listNode, array $data) |
|
45
|
|
|
{ |
|
46
|
1 |
|
foreach ($data as $key => $value) { |
|
47
|
1 |
|
if (is_array($value)) { |
|
48
|
1 |
|
$childNode = $document->createElement(is_int($key) ? Inflector::singularize($listNode->nodeName) : $key); |
|
49
|
1 |
|
$this->dataToNodes($document, $childNode, $value); |
|
50
|
|
|
} else { |
|
51
|
1 |
|
$childNode = $document->createElement($key, $this->getValueAsString($value)); |
|
52
|
1 |
|
$childNode->setAttribute('type', gettype($value)); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
1 |
|
$listNode->appendChild($childNode); |
|
56
|
|
|
} |
|
57
|
1 |
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** |
|
60
|
|
|
* @param bool|float|int|string $value |
|
61
|
|
|
* @return string |
|
62
|
|
|
*/ |
|
63
|
1 |
|
private function getValueAsString($value): string |
|
64
|
|
|
{ |
|
65
|
1 |
|
$type = gettype($value); |
|
66
|
|
|
|
|
67
|
1 |
|
if ('boolean' === $type) { |
|
68
|
1 |
|
return $value ? 'true' : 'false'; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
1 |
|
return (string) $value; |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|