-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimpleXMLReader.php
540 lines (465 loc) · 12 KB
/
SimpleXMLReader.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
<?php
/**
* SimpleXMLReader - extends for XMLReader class features
*
* I just wanted to make an easy way to iterate over all the nodes
* via foreach in an XML document and this is what I came up with.
*
* Remember!!! The main class XMLReader can going only forward
* that why you can't read previous elements! Organize your code wisely
*
* Copyright (C) 2022 Denik <https://denik.od.ua>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* @package SimpleXMLReader
* @author Denik
* @version 0.1.0
* @link https://denik.od.ua/
* @license AGPL-3.0-or-later <https://spdx.org/licenses/AGPL-3.0-or-later>
* @copyright Copyright (c) 2022
* @property XMLReader|string|null Class of cursor pointer | uri | XML source | null
*/
class SimpleXMLReader implements Iterator {
/**
* @var XMLReader
*/
private $reader;
private $readerVariables = array(
'path' => array(),
'index' => 0,
'skipNextRead' => false,
/**
* stores the result of the last XMLReader::read() operation.
* @var bool
*/
'lastRead' => true
);
public $debug = false;
/**
* cache for expansion into SimpleXMLElement
*
* @var null|SimpleXMLElement
* @see asSimpleXML
*/
private $simpleXML;
/**
* @var int
*/
private $stopDepth = 0;
private $stopIteration = false;
private $rewindLock = false;
public function __construct($source = null, $encoding = null, $flags = 0)
{
if ($source instanceof XMLReader)
{
$this->reader = $source;
}
else
{
$this->reader = new XMLReader;
if ($source && is_string($source))
{
// Check $source is file or url
if (strlen($source) < 4096 && ! preg_match('/[\x00-\x1F\x80-\xFF]/', $source)
&& (filter_var($source, FILTER_VALIDATE_URL)
|| file_exists($source)
)
) {
$this->reader->open($source, $encoding, $flags);
}
else
{
$this->reader->XML($source, $encoding, $flags);
}
}
}
// Create public variables
foreach ($this->readerVariables as $key => $value)
{
if (isset($this->reader->$key)) continue;
$this->reader->$key = $value;
}
}
/**
* decorate method calls
*
* @param string $name
* @param array $args
*
* @return mixed
*/
public function __call($name, $args)
{
return call_user_func_array(array($this->reader, $name), $args);
}
/**
* @param string $name
* @return bool
*/
public function __isset($name)
{
return isset($this->reader->$name);
}
/**
* decorate property get
*
* @param string $name
*
* @return mixed
*/
public function __get($name)
{
return $this->reader->$name;
}
/**
* @param string $name
* @param mixed $value
* @return void
*/
public function __set($name, $value)
{
throw new BadMethodCallException('XMLReader properties are read-only: ' . $name);
}
/**
* String of element
*
* @return string
*/
public function __toString()
{
return $this->readString();
}
/**
* Initialize iterator - find and read first element
*
* @return bool
*/
public function rewind()
{
if ($this->stopIteration) return false;
// Onetime call for object
if ($this->rewindLock) return false;
$this->rewindLock = true;
if ($this->reader->skipNextRead)
{
$this->reader->skipNextRead = false;
if ($this->debug) echo "{{$this->stopDepth},rewind=skip}\n";
}
else
{
$this->readElement();
if ($this->debug) echo "{{$this->stopDepth},rewind=element}\n";
}
if ( ! $this->valid())
{
$this->stopIteration = true;
$this->reader->skipNextRead = $this->depth < $this->stopDepth;
}
return true;
}
/**
* Index of read iteration
*
* @return void
*/
public function key()
{
return $this->reader->index;
}
/**
* Returns object of current element
*
* @return object
*/
public function current()
{
$current = clone $this;
$current->stopDepth = $current->depth + 1;
$current->rewindLock = false;
if ($this->debug) echo "{{$this->stopDepth},current}\n";
return $current;
}
/**
* Move to next element
*
* @param null|string $name name of element or emply
* @return bool
*/
public function next($name = null)
{
if ($this->stopIteration) return false;
// For while construction
if ( ! $this->rewindLock)
{
return $this->rewind();
}
if ($this->reader->skipNextRead)
{
$this->reader->skipNextRead = false;
// Skip next again if need
if ( ! $this->valid())
{
$this->stopIteration = true;
$this->reader->skipNextRead = $this->depth < $this->stopDepth;
}
if ($this->debug) echo "{{$this->stopDepth},next=skip}\n";
return true;
}
if ($this->debug) echo "{{$this->stopDepth},next=next}\n";
$b = $this->nextElement($name);
while($this->depth > $this->stopDepth && $b) {
$b = $this->nextElement($name);
}
$this->reader->skipNextRead = $this->depth < $this->stopDepth;
return $this->valid();
}
/**
* Check current object have elements for iteration
*
* @return bool
*/
public function valid()
{
$valid = $this->reader->lastRead && $this->depth === $this->stopDepth;
if ($this->debug) echo "{{$this->stopDepth},valid=".var_export($valid, true).",lastRead=".var_export($this->reader->lastRead, true)."}\n";
return $valid;
}
/**
* Get current element attributes
*
* @return array
*/
public function getAttributes()
{
// Parse attributes
$attributes = array();
if ($this->reader->hasAttributes)
{
while ($this->reader->moveToNextAttribute())
{
$attributes[$this->reader->name] = $this->reader->value;
}
}
$this->reader->moveToElement();
return $attributes;
}
/**
* Get Reader object
*
* @return XMLReader
*/
public function getReader()
{
return $this->reader;
}
/**
* Current node type as text
*
* @return string
*/
public function nodeTypeText($type = null)
{
if ($type === null) $type = $this->nodeType;
switch ($type) {
case XMLReader::NONE: return 'NONE'; break;
case XMLReader::ELEMENT: return 'ELEMENT'; break;
case XMLReader::ATTRIBUTE: return 'ATTRIBUTE'; break;
case XMLReader::TEXT: return 'TEXT'; break;
case XMLReader::CDATA: return 'CDATA'; break;
case XMLReader::ENTITY_REF: return 'ENTITY_REF'; break;
case XMLReader::ENTITY: return 'ENTITY'; break;
case XMLReader::PI: return 'PI'; break;
case XMLReader::COMMENT: return 'COMMENT'; break;
case XMLReader::DOC: return 'DOC'; break;
case XMLReader::DOC_TYPE: return 'DOC_TYPE'; break;
case XMLReader::DOC_FRAGMENT: return 'DOC_FRAGMENT'; break;
case XMLReader::NOTATION: return 'NOTATION'; break;
case XMLReader::WHITESPACE: return 'WHITESPACE'; break;
case XMLReader::SIGNIFICANT_WHITESPACE: return 'SIGNIFICANT_WHITESPACE'; break;
case XMLReader::END_ELEMENT: return 'END_ELEMENT'; break;
case XMLReader::END_ENTITY: return 'END_ENTITY'; break;
case XMLReader::XML_DECLARATION: return 'XML_DECLARATION'; break;
}
return 'UNKNOWN';
}
/**
* Interface for XMLReader::read()
*
* @return bool
*/
public function read()
{
$this->reader->index++;
$this->reader->lastRead = $this->reader->read();
$this->setPath();
return $this->reader->lastRead;
}
/**
* Read node by type
*
* @return bool
*/
public function readByNodeType($nodeType)
{
// Find by node type
while ($this->read()) {
if ($this->nodeType === $nodeType)
return true;
}
return false;
}
/**
* Read element
*
* @return bool
*/
public function readElement()
{
// Find first next Element
return $this->readByNodeType(XMLReader::ELEMENT);
}
/**
* Interface for XMLReader::next()
*
* @return bool
*/
public function nextNode($name = null)
{
$this->reader->index++;
$this->reader->lastRead = $name !== null ? $this->reader->next($name) : $this->reader->next();
$this->setPath();
return $this->reader->lastRead;
}
public function nextByNodeType($nodeType, $name = null)
{
// Find by node type
while ($this->nextNode($name)) {
if ($this->nodeType === $nodeType)
return true;
}
return false;
}
public function nextElement($name = null)
{
// Find next Element on this depth
return $this->nextByNodeType(XMLReader::ELEMENT, $name);
}
private function setPath()
{
if ($this->nodeType === XMLReader::ELEMENT)
{
$this->reader->path[$this->depth] = $this->name;
if (count($this->reader->path) !== $this->depth + 1) {
$this->reader->path = array_slice($this->reader->path, 0, $this->depth + 1);
}
}
}
public function getPath($asArray = false)
{
if ($asArray) return $this->reader->path;
return '/' . implode('/', $this->reader->path);
}
/**
* Decorated method
*
* @throws BadMethodCallException in case XMLReader can not expand the node
* @return string
*/
public function readOuterXml()
{
// Compatibility libxml 20620 (2.6.20) or later - LIBXML_VERSION / LIBXML_DOTTED_VERSION
if (method_exists($this->reader, 'readOuterXml')) {
return $this->reader->readOuterXml();
}
if (0 === $this->reader->nodeType) {
return '';
}
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
$node = $this->expand($doc);
return $doc->saveXML($node);
}
/**
* XMLReader expand node and import it into a DOMNode with a DOMDocument
*
* This is for example useful for DOMDocument::saveXML() {@see readOuterXml}
* or getting a SimpleXMLElement out of it {@see getSimpleXMLElement}
*
* @param DOMNode $baseNode
* @throws BadMethodCallException
* @return DOMNode
*/
public function expand(DOMNode $baseNode = null)
{
if (null === $baseNode) {
$baseNode = new DomDocument();
}
if ($baseNode instanceof DOMDocument) {
$doc = $baseNode;
} else {
$doc = $baseNode->ownerDocument;
if (null === $doc) {
throw new InvalidArgumentException('BaseNode has no OwnerDocument.');
}
}
if (false === $node = $this->reader->expand($baseNode)) {
throw new BadMethodCallException('Unable to expand node.');
}
if ($node->ownerDocument !== $doc) {
$node = $doc->importNode($node, true);
}
return $node;
}
/**
* Decorated method
*
* @throws BadMethodCallException
* @return string
*/
public function readString()
{
// Compatibility libxml 20620 (2.6.20) or later - LIBXML_VERSION / LIBXML_DOTTED_VERSION
if (method_exists($this->reader, 'readString')) {
return trim($this->reader->readString());
}
if (0 === $this->reader->nodeType) {
return '';
}
if (false === $node = $this->reader->expand()) {
throw new BadMethodCallException('Unable to expand node.');
}
return trim($node->textContent);
}
/**
* SimpleXMLElement for XMLReader::ELEMENT
*
* @param string $className SimpleXMLElement class name of the simplexml element
* @return SimpleXMLElement|null in case the current node can not be converted into a SimpleXMLElement
* @since 0.1.0
*/
public function getSimpleXMLElement($className = null)
{
if (null === $this->simpleXML) {
if ($this->reader->nodeType !== XMLReader::ELEMENT) {
return null;
}
$this->simpleXML = simplexml_import_dom($this->expand(), $className);
}
if (is_string($className) && !($this->simpleXML instanceof $className)) {
$this->simpleXML = simplexml_import_dom(dom_import_simplexml($this->simpleXML), $className);
}
return $this->simpleXML;
}
}