|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace UCD\Infrastructure\Repository\CharacterRepository\XMLRepository\CodepointElementReader; |
|
4
|
|
|
|
|
5
|
|
|
use UCD\Infrastructure\Repository\CharacterRepository\XMLRepository\CodepointElementReader; |
|
6
|
|
|
use UCD\Infrastructure\Repository\CharacterRepository\XMLRepository\XMLReader; |
|
7
|
|
|
|
|
8
|
|
|
final class StreamingReader implements CodepointElementReader |
|
9
|
|
|
{ |
|
10
|
|
|
const ELEMENT_CHARACTER = 'char'; |
|
11
|
|
|
const ELEMENT_NON_CHARACTER = 'noncharacter'; |
|
12
|
|
|
const ELEMENT_SURROGATE = 'surrogate'; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* @var array |
|
16
|
|
|
*/ |
|
17
|
|
|
private static $elements = [ |
|
18
|
|
|
self::ELEMENT_CHARACTER => true, |
|
19
|
|
|
self::ELEMENT_NON_CHARACTER => true, |
|
20
|
|
|
self::ELEMENT_SURROGATE => true |
|
21
|
|
|
]; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @var XMLReader |
|
25
|
|
|
*/ |
|
26
|
|
|
private $xmlReader; |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* @param XMLReader $xmlReader |
|
30
|
|
|
*/ |
|
31
|
|
|
public function __construct(XMLReader $xmlReader) |
|
32
|
|
|
{ |
|
33
|
|
|
$this->xmlReader = $xmlReader; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* {@inheritDoc} |
|
38
|
|
|
*/ |
|
39
|
|
|
public function read() |
|
40
|
|
|
{ |
|
41
|
|
|
$this->preRead(); |
|
42
|
|
|
|
|
43
|
|
|
try { |
|
44
|
|
|
while ($element = $this->readNext()) { |
|
45
|
|
|
yield $element; |
|
46
|
|
|
} |
|
47
|
|
|
} finally { |
|
48
|
|
|
$this->postRead(); |
|
49
|
|
|
} |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
private function preRead() |
|
53
|
|
|
{ |
|
54
|
|
|
$this->xmlReader->reopen(); |
|
55
|
|
|
|
|
56
|
|
|
while ($this->cursorHasElement() !== true) { |
|
57
|
|
|
$this->xmlReader->read(); |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
private function postRead() |
|
62
|
|
|
{ |
|
63
|
|
|
$this->xmlReader->close(); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
/** |
|
67
|
|
|
* @return bool |
|
68
|
|
|
*/ |
|
69
|
|
|
private function cursorHasElement() |
|
70
|
|
|
{ |
|
71
|
|
|
return $this->xmlReader->nodeType === XMLReader::ELEMENT |
|
72
|
|
|
&& array_key_exists($this->xmlReader->name, self::$elements); |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
|
|
/** |
|
76
|
|
|
* @return \DOMElement|null |
|
77
|
|
|
*/ |
|
78
|
|
|
private function readNext() |
|
79
|
|
|
{ |
|
80
|
|
|
if (!$this->cursorHasElement()) { |
|
81
|
|
|
return null; |
|
82
|
|
|
} |
|
83
|
|
|
|
|
84
|
|
|
$element = $this->xmlReader->expand(); |
|
85
|
|
|
$this->moveToNextElement(); |
|
86
|
|
|
|
|
87
|
|
|
return $element; |
|
88
|
|
|
} |
|
89
|
|
|
|
|
90
|
|
|
private function moveToNextElement() |
|
91
|
|
|
{ |
|
92
|
|
|
while ($this->xmlReader->next() !== false) { |
|
93
|
|
|
if ($this->cursorHasElement()) { |
|
94
|
|
|
break; |
|
95
|
|
|
} |
|
96
|
|
|
} |
|
97
|
|
|
} |
|
98
|
|
|
} |