1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ghc\Rosetta\Messages; |
4
|
|
|
|
5
|
|
|
use DOMDocument; |
6
|
|
|
use DOMNode; |
7
|
|
|
|
8
|
|
|
class Xml extends Message |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @return string |
12
|
|
|
*/ |
13
|
|
|
public function newData() |
14
|
|
|
{ |
15
|
|
|
return '<xml></xml>'; |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Get the instance as an array. |
20
|
|
|
* |
21
|
|
|
* @return array |
22
|
|
|
*/ |
23
|
|
View Code Duplication |
public function toArray() |
|
|
|
|
24
|
|
|
{ |
25
|
|
|
libxml_use_internal_errors(true); |
26
|
|
|
$root = new DOMDocument(); |
27
|
|
|
$root->preserveWhiteSpace = false; |
28
|
|
|
$root->loadXML($this->getData()); |
29
|
|
|
|
30
|
|
|
return $this->domNodeToArray($root); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param array $data |
35
|
|
|
* |
36
|
|
|
* @return self |
37
|
|
|
*/ |
38
|
|
|
public function fromArray($data) |
39
|
|
|
{ |
40
|
|
|
return $this; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param DomNode $root |
45
|
|
|
* |
46
|
|
|
* @return array |
47
|
|
|
*/ |
48
|
|
|
protected function domNodeToArray($root) |
49
|
|
|
{ |
50
|
|
|
$result = []; |
51
|
|
|
|
52
|
|
|
if ($root->hasAttributes()) { |
53
|
|
|
$attrs = $root->attributes; |
54
|
|
|
foreach ($attrs as $attr) { |
55
|
|
|
$result['@attributes'][$attr->name] = $attr->value; |
56
|
|
|
} |
57
|
|
|
} else { |
58
|
|
|
$result['@attributes'] = []; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
if ($root->hasChildNodes()) { |
62
|
|
|
$children = $root->childNodes; |
63
|
|
|
if ($children->length == 1) { |
64
|
|
|
$child = $children->item(0); |
65
|
|
|
if ($child->nodeType == XML_TEXT_NODE) { |
66
|
|
|
$result['_value'] = $child->nodeValue; |
67
|
|
|
|
68
|
|
|
return $result; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
$groups = []; |
72
|
|
|
foreach ($children as $child) { |
73
|
|
|
if (!isset($result[$child->nodeName])) { |
74
|
|
|
$result[$child->nodeName] = $this->domNodeToArray($child); |
75
|
|
|
} else { |
76
|
|
|
if (!isset($groups[$child->nodeName])) { |
77
|
|
|
$result[$child->nodeName] = [$result[$child->nodeName]]; |
78
|
|
|
$groups[$child->nodeName] = 1; |
79
|
|
|
} |
80
|
|
|
$result[$child->nodeName][] = $this->domNodeToArray($child); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
return $result; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.