| Current Path : /srv/web/sites/trentinoplant.it/httpdocs/vendor/phpgt/dom/src/ |
| Current File : /srv/web/sites/trentinoplant.it/httpdocs/vendor/phpgt/dom/src/XPathResult.php |
<?php
namespace Gt\Dom;
use DOMXPath;
use Gt\Dom\Exception\XPathQueryException;
use Iterator;
/**
* The XPathResult interface represents the results generated by evaluating an
* XPath expression within the context of a given node. Since XPath expressions
* can result in a variety of result types, this interface makes it possible to
* determine and handle the type and value of the result.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/XPathResult
*
* @implements Iterator<Node|Element>
*/
class XPathResult implements Iterator {
private NodeList $nodeList;
private int $iteratorKey;
public function __construct(
string $query,
Document $document,
Node|Element $context
) {
$xpath = new DOMXPath($document);
$result = $xpath->query($query, $context);
if(!$result) {
throw new XPathQueryException("Query is malformed: $query");
}
$nodeArray = [];
for($i = 0, $len = $result->length; $i < $len; $i++) {
/** @var Node|Element $item */
$item = $result->item($i);
array_push($nodeArray, $item);
}
$this->nodeList = NodeListFactory::create(...$nodeArray);
$this->iteratorKey = 0;
}
/**
* The iterateNext() method of the XPathResult interface iterates over
* a node set result and returns the next node from it or null if there
* are no more nodes.
*
* @return ?Node The next Node within the node set of the XPathResult.
* @link https://developer.mozilla.org/en-US/docs/Web/API/XPathResult/iterateNext
*/
public function iterateNext():null|Node|Element|Attr|Text {
$current = $this->current();
$this->next();
return $current;
}
public function current():null|Node|Element|Attr|Text {
return $this->nodeList->item($this->iteratorKey);
}
public function next():void {
$this->iteratorKey++;
}
public function key():int {
return $this->iteratorKey;
}
public function valid():bool {
return $this->nodeList->length > $this->iteratorKey;
}
public function rewind():void {
$this->iteratorKey = 0;
}
}