1
|
|
|
<?php |
2
|
|
|
namespace FluentDOM\XMLReader { |
3
|
|
|
|
4
|
|
|
use FluentDOM\XMLReader; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* Class Iterator |
8
|
|
|
* |
9
|
|
|
* It will use XMLReader::read() to iterate the nodes and use expand to return each found node as DOM node. |
10
|
|
|
*/ |
11
|
|
|
class Iterator implements \Iterator { |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* @var XMLReader |
15
|
|
|
*/ |
16
|
|
|
private $_reader; |
17
|
|
|
/** |
18
|
|
|
* @var string|NULL |
19
|
|
|
*/ |
20
|
|
|
private $_name; |
21
|
|
|
/** |
22
|
|
|
* @var callable |
23
|
|
|
*/ |
24
|
|
|
private $_filter; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @var int |
28
|
|
|
*/ |
29
|
|
|
private $_key = -1; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @var NULL|\DOMNode |
33
|
|
|
*/ |
34
|
|
|
private $_current = NULL; |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Iterator constructor. |
38
|
|
|
* |
39
|
|
|
* @param XMLReader $reader |
40
|
|
|
* @param NULL|string $name tag name filter |
41
|
|
|
* @param callable|NULL $filter |
42
|
|
|
*/ |
43
|
2 |
|
public function __construct( |
44
|
|
|
XMLReader $reader, $name = NULL, callable $filter = NULL |
45
|
|
|
) { |
46
|
2 |
|
$this->_reader = $reader; |
47
|
2 |
|
$this->_name = $name; |
48
|
2 |
|
$this->_filter = $filter; |
49
|
2 |
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* Throw an exception if rewind() is called after next() |
53
|
|
|
*/ |
54
|
2 |
|
public function rewind() { |
55
|
2 |
|
if ($this->_key >= 0) { |
56
|
1 |
|
throw new \LogicException(sprintf('%s is not a seekable iterator', __CLASS__)); |
57
|
|
|
} |
58
|
2 |
|
$this->next(); |
59
|
2 |
|
} |
60
|
|
|
|
61
|
2 |
|
public function next() { |
62
|
2 |
|
if ($this->move($this->_reader, $this->_name, $this->_filter)) { |
63
|
2 |
|
$this->_current = (NULL === $this->_current) |
64
|
2 |
|
? $this->_reader->expand() |
65
|
2 |
|
: $this->_reader->expand($this->_current->ownerDocument); |
66
|
2 |
|
$this->_key++; |
67
|
|
|
} else { |
68
|
2 |
|
$this->_current = NULL; |
69
|
|
|
} |
70
|
2 |
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* @param XMLReader $reader |
74
|
|
|
* @param string|NULL $name |
75
|
|
|
* @param callable|NULL $filter |
76
|
|
|
* @return bool |
77
|
|
|
*/ |
78
|
2 |
|
protected function move(XMLReader $reader, $name, $filter): bool { |
79
|
2 |
|
return $reader->read($name, NULL, $filter); |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
/** |
83
|
|
|
* @return bool |
84
|
|
|
*/ |
85
|
2 |
|
public function valid(): bool { |
86
|
2 |
|
return NULL !== $this->_current; |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
/** |
90
|
|
|
* @return \DOMNode|NULL |
91
|
|
|
*/ |
92
|
2 |
|
public function current() { |
93
|
2 |
|
return $this->_current; |
94
|
|
|
} |
95
|
|
|
|
96
|
|
|
/** |
97
|
|
|
* @return int |
98
|
|
|
*/ |
99
|
2 |
|
public function key(): int { |
100
|
2 |
|
return $this->_key; |
101
|
|
|
} |
102
|
|
|
} |
103
|
|
|
} |
104
|
|
|
|