index/src/Data/DbResultIterator.php

57 lines
1.3 KiB
PHP

<?php
// DbResultIterator.php
// Created: 2024-02-06
// Updated: 2024-02-06
namespace Index\Data;
use InvalidArgumentException;
use Iterator;
/**
* Implements an iterator and constructor wrapper for IDbResult.
*/
class DbResultIterator implements Iterator {
private bool $wasValid;
private object $current;
/**
* Call this through an IDbResult instance instead!
*
* @param IDbResult $result Result to operate on.
* @param callable(IDbResult): object $construct Constructor callback.
*/
public function __construct(
private IDbResult $result,
private $construct
) {
if(!is_callable($construct))
throw new InvalidArgumentException('$construct must be a callable.');
}
public function current(): mixed {
return $this->current;
}
public function key(): mixed {
return spl_object_id($this->current);
}
private function moveNext(): void {
if($this->wasValid = $this->result->next())
$this->current = ($this->construct)($this->result);
}
public function next(): void {
$this->moveNext();
}
public function rewind(): void {
$this->moveNext();
}
public function valid(): bool {
return $this->wasValid;
}
}