1 | <?php |
||
19 | class XmlExportService |
||
20 | { |
||
21 | /** |
||
22 | * @var XmlConvertibleInterface |
||
23 | */ |
||
24 | public $object; |
||
25 | |||
26 | /** |
||
27 | * @var \DOMDocument |
||
28 | */ |
||
29 | public $document; |
||
30 | |||
31 | /** |
||
32 | * XmlExportService constructor. |
||
33 | * @param XmlConvertibleInterface $object |
||
34 | * @param \DOMDocument|null $document |
||
35 | */ |
||
36 | 14 | public function __construct(XmlConvertibleInterface $object, \DOMDocument $document = null) |
|
37 | { |
||
38 | 14 | $this->setDocument($document) |
|
39 | 14 | ->setObject($object); |
|
40 | 14 | } |
|
41 | |||
42 | /** |
||
43 | * Converting object to \DOMElement |
||
44 | * |
||
45 | 14 | * @return \DOMElement |
|
46 | */ |
||
47 | 14 | public function export() |
|
48 | 14 | { |
|
49 | $xml = $this->createElement(); |
||
50 | |||
51 | 14 | Collection::from($this->getObject()->getXmlChildren() ?? []) |
|
52 | ->map($this->mapChild()) |
||
53 | 6 | ->forEach(function (\DOMNode $child) use ($xml) { |
|
54 | 5 | $xml->appendChild($child); |
|
55 | 6 | }); |
|
56 | 13 | ||
57 | |||
58 | 6 | Collection::from($this->getObject()->getXmlProperties()) |
|
59 | 13 | ->reduce(function (Collection $properties, string $property) { |
|
60 | $properties[$property] = $this->getObject()->{$property}; |
||
61 | return $properties; |
||
62 | 13 | }, Collection::create()) |
|
63 | ->filter($this->getIsAttribute()) |
||
64 | 7 | ->forEach(function ($value, string $property) use ($xml) { |
|
65 | 7 | $xml->setAttribute($property, $value); |
|
66 | 13 | }); |
|
67 | |||
68 | 7 | return $xml; |
|
69 | 13 | } |
|
70 | 13 | ||
71 | 6 | /** |
|
72 | 13 | * Creating new element to put object into |
|
73 | * |
||
74 | 13 | * @return \DOMElement |
|
75 | */ |
||
76 | protected function createElement() :\DOMElement |
||
77 | { |
||
78 | return $this->getDocument()->createElement( |
||
79 | $this->getObject()->getXmlElementName() |
||
80 | 14 | ); |
|
81 | } |
||
82 | 14 | ||
83 | /** |
||
84 | * Preparing all children to export |
||
85 | * |
||
86 | * @return \Closure |
||
87 | */ |
||
88 | protected function mapChild() :\Closure |
||
89 | 14 | { |
|
90 | function ($child) { |
||
91 | 14 | return $child instanceof XmlConvertibleInterface |
|
92 | 14 | ? $child->toXml($this->document) |
|
93 | : $child; |
||
94 | } |
||
95 | } |
||
|
|||
96 | |||
97 | /** |
||
98 | 14 | * Can we put current attribute to XML |
|
99 | * |
||
100 | 14 | * @return \Closure |
|
101 | */ |
||
102 | protected function getIsAttribute() :\Closure{ |
||
103 | return function ($value): bool { |
||
104 | return !is_array($value) && !is_object($value) && !is_null($value); |
||
105 | }; |
||
106 | } |
||
107 | 14 | ||
108 | /** |
||
109 | 14 | * @return XmlConvertibleInterface |
|
110 | 14 | */ |
|
111 | public function getObject(): XmlConvertibleInterface |
||
112 | { |
||
113 | return $this->object; |
||
143 | } |