Skip to content

Commit 43d3bc3

Browse files
authored
Merge pull request #10 from elecena/add/iterateByNodeContent
XMLParser: introduce the iterateByNodeContent() helper
2 parents 6ba41b0 + 6c2d331 commit 43d3bc3

File tree

3 files changed

+36
-6
lines changed

3 files changed

+36
-6
lines changed

src/XMLParser.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace Elecena\XmlIterator;
44

55
use Elecena\XmlIterator\Exceptions\ParsingError;
6+
use Elecena\XmlIterator\Nodes\XMLNodeContent;
67

78
/**
89
* Implements a fast and memory-efficient XML parser with the iterator interface.
@@ -181,4 +182,19 @@ private function parseNextChunk(): void
181182
$this->close();
182183
}
183184
}
185+
186+
/**
187+
* Parses the XML and yields only the @see XMLNodeContent items with matching node name
188+
*
189+
* @param string $name
190+
* @return \Generator<XMLNodeContent>
191+
*/
192+
public function iterateByNodeContent(string $name): \Generator
193+
{
194+
foreach($this as $node) {
195+
if ($node instanceof XMLNodeContent && $node->name === $name) {
196+
yield $node;
197+
}
198+
}
199+
}
184200
}

tests/XMLParserCDataTest.php

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,12 +28,10 @@ public function testCDataIsProperlyParsed(): void
2828
{
2929
$node = null;
3030

31-
foreach ($this->getParser() as $item) {
32-
if ($item instanceof XMLNodeContent && $item->name === 'description') {
33-
if (trim($item->content) !== '') {
34-
$node = $item;
35-
break;
36-
}
31+
foreach ($this->getParser()->iterateByNodeContent(name: 'description') as $item) {
32+
if (trim($item->content) !== '') {
33+
$node = $item;
34+
break;
3735
}
3836
}
3937

tests/XMLParserLargeFileTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,20 @@ public function testParsesTheUrls(): void
2626
$this->assertCount(1857, $locations);
2727
$this->assertEquals(1857, $urlTagsCounter);
2828
}
29+
30+
public function testIterateByNodeContent()
31+
{
32+
$cnt = 0;
33+
34+
// <url><loc>https://sklepzamel.com/produkt/sonda-temperatury-ntc-03/</loc></url>
35+
foreach($this->getParser()->iterateByNodeContent(name: 'loc') as $node) {
36+
$this->assertInstanceOf(XMLNodeContent::class, $node);
37+
$this->assertEquals('loc', $node->name);
38+
$this->assertStringStartsWith('http', $node->content);
39+
40+
$cnt++;
41+
}
42+
43+
$this->assertEquals(1857, $cnt);
44+
}
2945
}

0 commit comments

Comments
 (0)