@@ -21,18 +21,22 @@ public function getSchema($resource)
21
21
}
22
22
23
23
/**
24
- * Fill the provided schema with an associative array data
24
+ * Fill the provided schema with an associative array data, also remove the useless XML nodes if the corresponding flag is true
25
25
*
26
26
* @param SimpleXMLElement $xmlSchema
27
27
* @param array $data
28
+ * @param bool $removeUselessNodes set true if you want to remove nodes that are not present in the data array
28
29
* @return SimpleXMLElement
29
30
*/
30
- public function fillSchema (SimpleXMLElement $ xmlSchema , $ data )
31
+ public function fillSchema (SimpleXMLElement $ xmlSchema , $ data, $ removeUselessNodes = true )
31
32
{
32
33
$ resource = $ xmlSchema ->children ()->children ();
33
34
foreach ($ data as $ key => $ value ) {
34
35
$ this ->processNode ($ resource , $ key , $ value );
35
36
}
37
+ if ($ removeUselessNodes ) {
38
+ $ this ->checkForUselessNode ($ resource , $ data );
39
+ }
36
40
return $ xmlSchema ;
37
41
}
38
42
@@ -82,4 +86,22 @@ private function processNode(SimpleXMLElement $node, $dataKey, $dataValue)
82
86
$ node ->$ dataKey = $ dataValue ;
83
87
}
84
88
}
89
+
90
+ /**
91
+ * Remove XML first level nodes that are not present int the data array
92
+ * @param SimpleXMLElement $resource
93
+ * @param $data
94
+ */
95
+ private function checkForUselessNode (SimpleXMLElement $ resource , $ data )
96
+ {
97
+ $ uselessNodes = [];
98
+ foreach ($ resource as $ key => $ value ) {
99
+ if (!array_key_exists ($ key , $ data )) {
100
+ $ uselessNodes [] = $ key ;
101
+ }
102
+ }
103
+ foreach ($ uselessNodes as $ key ) {
104
+ unset($ resource ->$ key );
105
+ }
106
+ }
85
107
}
0 commit comments