<?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();
    }
}