1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Class XmlResponse | XmlResponse.php |
4
|
|
|
* @package Faulancer\Http |
5
|
|
|
* @author Florian Knapp <[email protected]> |
6
|
|
|
*/ |
7
|
|
|
namespace Faulancer\Http; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Class XmlResponse |
11
|
|
|
*/ |
12
|
|
|
class XmlResponse extends Response |
13
|
|
|
{ |
14
|
|
|
|
15
|
|
|
/** @var array */ |
16
|
|
|
protected $content = []; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @param array $data |
20
|
|
|
* @param \SimpleXMLElement $xml |
21
|
|
|
* @codeCoverageIgnore |
22
|
|
|
*/ |
23
|
|
|
private function convertArrayToXml(\SimpleXMLElement &$xml, $data) |
24
|
|
|
{ |
25
|
|
|
foreach ($data as $key=>$value) { |
26
|
|
|
|
27
|
|
|
if(is_numeric($key)) { |
28
|
|
|
$key = 'item' . $key; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
if(is_array($value['value'])) { |
32
|
|
|
|
33
|
|
|
$node = $this->generateNode($xml, $key, $value); |
34
|
|
|
$this->convertArrayToXml($node, $value['value']); |
|
|
|
|
35
|
|
|
|
36
|
|
|
} else { |
37
|
|
|
$this->generateNode($xml, $key, $value); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
} |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param \SimpleXMLElement $xml |
45
|
|
|
* @param string $key |
46
|
|
|
* @param null|array $value |
47
|
|
|
* @return null|\SimpleXMLElement |
48
|
|
|
* @codeCoverageIgnore |
49
|
|
|
*/ |
50
|
|
|
private function generateNode(\SimpleXMLElement &$xml, $key, $value = null) |
51
|
|
|
{ |
52
|
|
|
$node = null; |
53
|
|
|
|
54
|
|
|
if (is_array($value) && in_array('@attributes', array_keys($value))) { |
55
|
|
|
|
56
|
|
|
$attributes = $value['@attributes']; |
57
|
|
|
|
58
|
|
|
if (!is_array($value['value'])) { |
59
|
|
|
$node = $xml->addChild($key, htmlspecialchars($value['value'])); |
60
|
|
|
} else { |
61
|
|
|
$node = $xml->addChild($key); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
foreach ($attributes as $attr => $val) { |
65
|
|
|
$node->addAttribute($attr, $val); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
return $node; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* @param array $content |
75
|
|
|
* @return self |
76
|
|
|
* @codeCoverageIgnore |
77
|
|
|
*/ |
78
|
|
|
public function setContent($content = []) |
79
|
|
|
{ |
80
|
|
|
$this->setResponseHeader(['Content-Base' => 'text/xml']); |
81
|
|
|
|
82
|
|
|
$xml = new \SimpleXMLElement('<?xml version="1.0"?><root></root>'); |
83
|
|
|
$this->convertArrayToXml($xml, $content); |
84
|
|
|
$result = $xml->asXml(); |
85
|
|
|
|
86
|
|
|
$this->content = $result; |
|
|
|
|
87
|
|
|
return $this; |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
} |
Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code: