Skip to content

Commit

Permalink
Merge pull request #10 from elecena/add/iterateByNodeContent
Browse files Browse the repository at this point in the history
XMLParser: introduce the iterateByNodeContent() helper
  • Loading branch information
macbre authored Aug 11, 2023
2 parents 6ba41b0 + 6c2d331 commit 43d3bc3
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 6 deletions.
16 changes: 16 additions & 0 deletions src/XMLParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Elecena\XmlIterator;

use Elecena\XmlIterator\Exceptions\ParsingError;
use Elecena\XmlIterator\Nodes\XMLNodeContent;

/**
* Implements a fast and memory-efficient XML parser with the iterator interface.
Expand Down Expand Up @@ -181,4 +182,19 @@ private function parseNextChunk(): void
$this->close();
}
}

/**
* Parses the XML and yields only the @see XMLNodeContent items with matching node name
*
* @param string $name
* @return \Generator<XMLNodeContent>
*/
public function iterateByNodeContent(string $name): \Generator
{
foreach($this as $node) {
if ($node instanceof XMLNodeContent && $node->name === $name) {
yield $node;
}
}
}
}
10 changes: 4 additions & 6 deletions tests/XMLParserCDataTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,10 @@ public function testCDataIsProperlyParsed(): void
{
$node = null;

foreach ($this->getParser() as $item) {
if ($item instanceof XMLNodeContent && $item->name === 'description') {
if (trim($item->content) !== '') {
$node = $item;
break;
}
foreach ($this->getParser()->iterateByNodeContent(name: 'description') as $item) {
if (trim($item->content) !== '') {
$node = $item;
break;
}
}

Expand Down
16 changes: 16 additions & 0 deletions tests/XMLParserLargeFileTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,20 @@ public function testParsesTheUrls(): void
$this->assertCount(1857, $locations);
$this->assertEquals(1857, $urlTagsCounter);
}

public function testIterateByNodeContent()
{
$cnt = 0;

// <url><loc>https://sklepzamel.com/produkt/sonda-temperatury-ntc-03/</loc></url>
foreach($this->getParser()->iterateByNodeContent(name: 'loc') as $node) {
$this->assertInstanceOf(XMLNodeContent::class, $node);
$this->assertEquals('loc', $node->name);
$this->assertStringStartsWith('http', $node->content);

$cnt++;
}

$this->assertEquals(1857, $cnt);
}
}

0 comments on commit 43d3bc3

Please sign in to comment.