|
11 | 11 |
|
12 | 12 | namespace FOS\RestBundle\Decoder; |
13 | 13 |
|
| 14 | +use Symfony\Component\Serializer\Encoder\XmlEncoder; |
| 15 | + |
14 | 16 | /** |
15 | 17 | * Decodes XML data |
16 | 18 | * |
|
20 | 22 | */ |
21 | 23 | class XmlDecoder implements DecoderInterface |
22 | 24 | { |
23 | | - /** |
24 | | - * {@inheritdoc} |
25 | | - */ |
26 | | - public function decode($data) |
27 | | - { |
28 | | - $xml = @simplexml_load_string($data); |
29 | | - if (!$xml) { |
30 | | - return; |
31 | | - } |
32 | | - |
33 | | - if (!$xml->count()) { |
34 | | - if (!$xml->attributes()) { |
35 | | - return (string) $xml; |
36 | | - } |
37 | | - $data = array(); |
38 | | - foreach ($xml->attributes() as $attrkey => $attr) { |
39 | | - $data['@'.$attrkey] = (string) $attr; |
40 | | - } |
41 | | - $data['#'] = (string) $xml; |
| 25 | + private $encoder; |
42 | 26 |
|
43 | | - return $data; |
44 | | - } |
45 | | - |
46 | | - return $this->parseXml($xml); |
| 27 | + public function __construct() |
| 28 | + { |
| 29 | + $this->encoder = new XmlEncoder(); |
47 | 30 | } |
48 | 31 |
|
49 | 32 | /** |
50 | | - * Parse the input SimpleXmlElement into an array |
51 | | - * |
52 | | - * @param \SimpleXmlElement $node xml to parse |
53 | | - * @return array |
| 33 | + * {@inheritdoc} |
54 | 34 | */ |
55 | | - private function parseXml(\SimpleXmlElement $node) |
| 35 | + public function decode($data) |
56 | 36 | { |
57 | | - $data = array(); |
58 | | - if ($node->attributes()) { |
59 | | - foreach ($node->attributes() as $attrkey => $attr) { |
60 | | - $data['@'.$attrkey] = (string) $attr; |
61 | | - } |
62 | | - } |
63 | | - foreach ($node->children() as $key => $subnode) { |
64 | | - if ($subnode->count()) { |
65 | | - $value = $this->parseXml($subnode); |
66 | | - } elseif ($subnode->attributes()) { |
67 | | - $value = array(); |
68 | | - foreach ($subnode->attributes() as $attrkey => $attr) { |
69 | | - $value['@'.$attrkey] = (string) $attr; |
70 | | - } |
71 | | - $value['#'] = (string) $subnode; |
72 | | - } else { |
73 | | - $value = (string) $subnode; |
74 | | - } |
75 | | - |
76 | | - if ($key === 'item') { |
77 | | - if (isset($value['@key'])) { |
78 | | - $data[(string)$value['@key']] = $value['#']; |
79 | | - } elseif (isset($data['item'])) { |
80 | | - $tmp = $data['item']; |
81 | | - unset($data['item']); |
82 | | - $data[] = $tmp; |
83 | | - $data[] = $value; |
84 | | - } |
85 | | - } elseif (array_key_exists($key, $data)) { |
86 | | - if ((false === is_array($data[$key])) || (false === isset($data[$key][0]))) { |
87 | | - $data[$key] = array($data[$key]); |
88 | | - } |
89 | | - $data[$key][] = $value; |
90 | | - } else { |
91 | | - $data[$key] = $value; |
92 | | - } |
93 | | - } |
94 | | - |
95 | | - return $data; |
| 37 | + return $this->encoder->decode($data, 'xml'); |
96 | 38 | } |
97 | 39 | } |
0 commit comments