1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace NilPortugues\Api\Xml; |
4
|
|
|
|
5
|
|
|
use DOMDocument; |
6
|
|
|
use SimpleXMLElement; |
7
|
|
|
|
8
|
|
|
class XmlPresenter |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @var array |
12
|
|
|
*/ |
13
|
|
|
private $linkKeys = [ |
14
|
|
|
XmlTransformer::LINKS_HREF, |
15
|
|
|
]; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @param array $array |
19
|
|
|
* |
20
|
|
|
* @return string |
21
|
|
|
*/ |
22
|
|
|
public function output(array $array) |
23
|
|
|
{ |
24
|
|
|
$xmlData = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><data></data>'); |
25
|
|
|
$this->arrayToXml($array, $xmlData); |
26
|
|
|
$xml = $xmlData->asXML(); |
27
|
|
|
$xmlDoc = new DOMDocument(); |
28
|
|
|
$xmlDoc->loadXML($xml); |
29
|
|
|
$xmlDoc->preserveWhiteSpace = false; |
30
|
|
|
$xmlDoc->formatOutput = true; |
31
|
|
|
$xmlDoc->substituteEntities = false; |
32
|
|
|
|
33
|
|
|
return rtrim(html_entity_decode($xmlDoc->saveXML()), "\n"); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Converts an array to XML using SimpleXMLElement. |
38
|
|
|
* |
39
|
|
|
* @param array $data |
40
|
|
|
* @param SimpleXMLElement $xmlData |
41
|
|
|
*/ |
42
|
|
|
protected function arrayToXml(array &$data, SimpleXMLElement $xmlData) |
43
|
|
|
{ |
44
|
|
|
foreach ($data as $key => $value) { |
45
|
|
|
$key = ltrim($key, '_'); |
46
|
|
|
if (\is_array($value)) { |
47
|
|
|
if (\is_numeric($key)) { |
48
|
|
|
$key = 'resource'; |
49
|
|
|
} |
50
|
|
|
if (false === empty($value[XmlTransformer::LINKS_HREF])) { |
51
|
|
|
$subnode = $xmlData->addChild('link'); |
52
|
|
|
$subnode->addAttribute('rel', $key); |
53
|
|
|
foreach ($this->linkKeys as $linkKey) { |
54
|
|
|
if (!empty($value[$linkKey])) { |
55
|
|
|
$subnode->addAttribute($linkKey, $value[$linkKey]); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
} else { |
59
|
|
|
if (!empty($value[XmlTransformer::LINKS][XmlTransformer::LINKS_HREF])) { |
60
|
|
|
$subnode = $xmlData->addChild('resource'); |
61
|
|
|
$subnode->addAttribute( |
62
|
|
|
XmlTransformer::LINKS_HREF, |
63
|
|
|
$value[XmlTransformer::LINKS][XmlTransformer::LINKS_HREF] |
64
|
|
|
); |
65
|
|
|
if ($key !== 'resource') { |
66
|
|
|
$subnode->addAttribute('rel', $key); |
67
|
|
|
} |
68
|
|
|
} else { |
69
|
|
|
$subnode = $xmlData->addChild($key); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
$this->arrayToXml($value, $subnode); |
73
|
|
|
} else { |
74
|
|
|
if ($key !== XmlTransformer::LINKS) { |
75
|
|
|
if ($value === true || $value === false) { |
76
|
|
|
$value = ($value) ? 'true' : 'false'; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
if ($key === XmlTransformer::LINKS_HREF) { |
80
|
|
|
break; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
$xmlData->addChild("$key", '<![CDATA['.html_entity_decode($value).']]>'); |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|