CachedPDOIterator: introduce rewindable PDOStatement iterator

This commit is contained in:
Aaron van Geffen 2025-05-13 22:51:12 +02:00
parent 8dbf1dce7b
commit 9989ba1fa7

View File

@ -0,0 +1,56 @@
<?php
/*****************************************************************************
* CachedPDOIterator.php
* Contains model class CachedPDOIterator.
*
* Based on https://gist.github.com/hakre/5152090
*
* Kabuki CMS (C) 2013-2021, Aaron van Geffen
*****************************************************************************/
class CachedPDOIterator extends CachingIterator
{
private $index;
public function __construct(PDOStatement $statement)
{
parent::__construct(new IteratorIterator($statement), self::FULL_CACHE);
}
public function rewind(): void
{
if ($this->index === null)
{
parent::rewind();
}
$this->index = 0;
}
public function current(): mixed
{
if ($this->offsetExists($this->index))
{
return $this->offsetGet($this->index);
}
return parent::current();
}
public function key(): mixed
{
return $this->index;
}
public function next(): void
{
$this->index++;
if (!$this->offsetExists($this->index))
{
parent::next();
}
}
public function valid(): bool
{
return $this->offsetExists($this->index) || parent::valid();
}
}