-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmergexml.php
356 lines (341 loc) · 12.3 KB
/
mergexml.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
<?php
/**
* XML merging class
* Merge multiple XML sources
*
* @package MergeXML
* @author Vallo Reima
* @copyright (C)2014
*/
class MergeXML {
private $cln = 'DOMDocument';
private $dom; /* result DOM object */
private $dxp; /* result xPath object */
private $nsp; /* namespaces list */
private $nsd = '_'; /* default namespace prefix */
private $ovw = array(
'stay' => array(), /* do not overwrite me */
'keep' => array() /* do not overwrite existing */
);
private $join; /* joining root name */
private $updn; /* update nodes sequentially by name */
private $count = 0; /* adding counter */
private $error; /* error info */
/**
* set (default) options, create result object
* @param array $opts -- stay, keep, join, updn, fmt, enc
*/
public function __construct($opts = array()) {
$this->Protect($opts);
$this->join = !isset($opts['join']) ? 'root' : (string) $opts['join'];
$this->updn = !isset($opts['updn']) ? true : (bool) $opts['updn'];
$this->error = (object) array('code' => '', 'text' => '');
if (class_exists($this->cln)) {
$this->dom = new $this->cln();
$this->dom->preserveWhiteSpace = false;
$this->dom->formatOutput = !isset($opts['fmt']) ? true : (bool) $opts['fmt'];
$this->dom->encoding = !isset($opts['enc']) ? 'utf-8' : (string) $opts['enc'];
} else {
$this->Error('nod');
}
}
/**
* add XML file
* @param string $file -- pathed filename
* @param array $opts
* @return object|false
*/
public function AddFile($file, $opts = array()) {
$this->Protect($opts);
$data = @file_get_contents($file);
if ($data === false) {
$rlt = $this->Error('nof');
} else if (empty($data)) {
$rlt = $this->Error('emf');
} else {
$rlt = $this->AddSource($data);
}
return $rlt;
}
/**
* add XML to result object
* @param string|object $xml
* @param array $opts
* @return mixed -- false - bad content
* object - result
*/
public function AddSource($xml, $opts = array()) {
$this->Protect($opts);
if (is_object($xml)) {
if (get_class($xml) != $this->cln) {
$dom = false;
} else if ($this->dom->hasChildNodes()) {
$dom = $xml;
} else {
$this->dom = $xml;
$this->dom->formatOutput = true;
$dom = true;
}
} else if ($this->dom->hasChildNodes()) { /* not first */
$dom = new $this->cln();
$dom->preserveWhiteSpace = false;
if (!@$dom->loadXML($xml)) {
$dom = false;
}
} else { /* first slot */
$dom = @$this->dom->loadXML($xml) ? true : false;
}
if ($dom === false) {
$rlt = $this->Error('inv');
} else if ($dom === true && $this->NameSpaces()) {
$this->count = 1;
$rlt = $this->dom;
} else if (is_object($dom) && $this->CheckSource($dom)) {
$this->Merge($dom, '/'); /* add to existing */
$this->count++;
$rlt = $this->dom;
} else {
$rlt = false;
}
return $rlt;
}
/**
* set stay/keep
* @param array $opt -- options
*/
private function Protect($opt) {
foreach ($this->ovw as $key => $val) {
if (isset($opt[$key])) {
if (is_array($opt[$key])) {
$this->ovw[$key] = array_merge($val, $opt[$key]);
} else if (!empty($opt[$key])) {
array_push($this->ovw[$key], $opt[$key]);
}
} else if (empty($this->ovw[$key])) {
array_push($this->ovw[$key], 'all');
}
}
}
/**
* check/modify root and namespaces,
* @param object $dom source
* @return {bool}
*/
private function CheckSource(&$dom) {
$rlt = true;
if (strcasecmp($dom->encoding, $this->dom->encoding) !== 0) {
$rlt = $this->Error('enc');
} else if ($dom->documentElement->namespaceURI != $this->dom->documentElement->namespaceURI) { /* $dom->documentElement->lookupnamespaceURI(NULL) */
$rlt = $this->Error('nse');
} else if ($dom->documentElement->nodeName != $this->dom->documentElement->nodeName) {
if (!$this->join) {
$rlt = $this->Error('dif');
} else if (is_string($this->join)) {
$doc = new DOMDocument();
$doc->encoding = $this->dom->encoding;
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
$xml = "<?xml version=\"{$this->dom->xmlVersion}\" encoding=\"{$this->dom->encoding}\"?><$this->join></$this->join>";
if (@$doc->loadXML($xml)) {
$tmp = $doc->importNode($this->dom->documentElement, true);
$doc->documentElement->appendChild($tmp);
$this->dom = $doc;
$this->join = true;
} else {
$rlt = $this->Error('jne');
$this->join = null;
}
}
}
if ($rlt) {
$doc = simplexml_import_dom($dom);
$rlt = $this->NameSpaces($doc->getDocNamespaces(true));
}
return $rlt;
}
/**
* register namespaces
* @param array $nsp -- additional namespaces
* @return bool
*/
private function NameSpaces($nsp = array()) {
$doc = simplexml_import_dom($this->dom);
$nsps = $doc->getDocNamespaces(true);
foreach ($nsp as $pfx => $url) {
if (!isset($nsps[$pfx])) {
$this->dom->createAttributeNS($url, "$pfx:attr");
$nsps[$pfx] = $url;
}
}
$this->dxp = new DOMXPath($this->dom);
$this->nsp = array();
$rlt = true;
foreach ($nsps as $pfx => $url) {
if ($pfx == $this->nsd) {
$rlt = $this->Error('nse');
break;
} else if (empty($pfx)) {
$pfx = $this->nsd;
}
$this->nsp[$pfx] = $url;
$this->dxp->registerNamespace($pfx, $url);
}
return $rlt;
}
/**
* join 2 dom objects
* @param object $src -- current source node
* @param object $pth -- current source path
*/
private function Merge($src, $pth) {
$i = 0;
foreach ($src->childNodes as $node) {
$path = $this->GetNodePath($src->childNodes, $node, $pth, $i);
$obj = $this->Query($path);
if ($node->nodeType === XML_ELEMENT_NODE) {
$flg = true; /* replace existing node by default */
if ($obj->length == 0 || $obj->item(0)->namespaceURI != $node->namespaceURI) { /* add node */
$tmp = $this->dom->importNode($node, true);
$this->Query($pth)->item(0)->appendChild($tmp);
} else {
if (array_search($obj->item(0)->getAttribute('stay'), $this->ovw['stay']) !== false ||
(array_search($node->getAttribute('keep'), $this->ovw['keep']) !== false &&
array_search($obj->item(0)->getAttribute('keep'), $this->ovw['keep']) === false)) {
$flg = false; /* don't replace */
}
if ($flg && $node->hasAttributes()) { /* add/replace attributes */
foreach ($node->attributes as $attr) {
$obj->item(0)->setAttribute($attr->nodeName, $attr->nodeValue);
}
}
}
if ($node->hasChildNodes() && $flg) {
$this->Merge($node, $path); /* recurse to subnodes */
}
} else if ($node->nodeType === XML_TEXT_NODE || $node->nodeType === XML_COMMENT_NODE) { /* leaf node */
if ($obj->length == 0) {
if ($node->nodeType === XML_TEXT_NODE) {
$tmp = $this->dom->createTextNode($node->nodeValue);
} else {
$tmp = $this->dom->createComment($node->nodeValue);
}
$this->Query($pth)->item(0)->appendChild($tmp);
} else {
$obj->item(0)->nodeValue = $node->nodeValue;
}
}
$i++;
}
}
/**
* form the node xPath expression
* @param {object} $nodes -- child nodes
* @param {object} $node -- current child
* @param {string} $pth -- parent path
* @param {int} $eln -- element sequence number
* @return {string} query path
*/
private function GetNodePath($nodes, $node, $pth, $eln) {
$j = 0;
if ($node->nodeType === XML_ELEMENT_NODE) {
$i = 0;
foreach ($nodes as $nde) {
if ($i > $eln) {
break;
} else if (($this->updn && $nde->nodeType === $node->nodeType && $nde->nodeName === $node->nodeName && $nde->namespaceURI === $node->namespaceURI) ||
(!$this->updn && $nde->nodeType !== XML_PI_NODE)) {
$j++;
}
$i++;
}
if ($this->updn) {
if ($node->prefix) {
$p = $node->prefix . ':';
} else if (isset($this->nsp[$this->nsd])) {
$p = $this->nsd . ':';
} else {
$p = '';
}
$p .= $node->localName;
} else {
$p = 'node()';
}
} else if ($node->nodeType === XML_TEXT_NODE || $node->nodeType === XML_COMMENT_NODE) {
$i = 0;
foreach ($nodes as $nde) {
if ($i > $eln) {
break;
} else if ($nde->nodeType === $node->nodeType) {
$j++;
}
$i++;
}
$p = $node->nodeType === XML_TEXT_NODE ? 'text()' : 'comment()';
} else {
$p = $pth;
}
if ($j > 0) {
$p = $pth . ($pth === '/' ? '' : '/') . $p . '[' . $j . ']';
}
return $p;
}
/**
* xPath query
* @param string $qry -- query statement
* @return object
*/
public function Query($qry) {
if ($this->join === true) {
$qry = "/{$this->dom->documentElement->nodeName}" . ($qry === '/' ? '' : $qry);
}
$rlt = $this->dxp->query($qry);
return $rlt;
}
/**
* get result
* @param {int} flg -- 0 - object
* 1 - xml
* 2 - html
* @return {mixed}
*/
public function Get($flg = 0) {
if ($flg == 0) {
$rlt = $this->dom;
} else {
$rlt = $this->dom->saveXML();
if ($flg == 2) {
$r = str_replace(' ', ' ', htmlspecialchars($rlt));
$rlt = str_replace(array("\r\n", "\n", "\r"), '<br />', $r);
}
}
return $rlt;
}
/**
* set error message
* @param string $err token
* @return false
*/
private function Error($err = 'und') {
$errs = array(
'nod' => "$this->cln is not supported",
'nof' => 'File not found',
'emf' => 'File is empty', /* possible delivery fault */
'inv' => 'Invalid XML source',
'enc' => 'Different encoding',
'dif' => 'Different root nodes',
'jne' => 'Invalid join parameter',
'nse' => 'Namespace incompatibility',
'und' => 'Undefined error');
$this->error->code = isset($errs[$err]) ? $err : 'und';
$this->error->text = $errs[$this->error->code];
return false;
}
/**
* get property value
* @param string $name
* @return mixed -- null - missing
*/
public function __get($name) {
return isset($this->$name) ? $this->$name : null;
}
}