<?php

declare(strict_types=1);

/**
 * Iterator over a list of [key, value] nodes, where the value is either data
 * to be wrapped in a Varien_Simplexml_Element or a child instance. Leaf nodes
 * will be returned as plain strings. The nodes will iterate over children.
 *
 * @template T
 * @implements Iterator<string, T>
 */
final class Varien_Simplexml_Iterator implements Iterator {

    /**
     * @param list<array{0:string, 1:array}> $iter
     * @param class-string<T> $elementClass
     */
    public function __construct(
        // We can't have this readonly since iterating it means we are modifying it
        private array $iter,
        private readonly string $elementClass
    ) {}

    public function rewind(): void {
        reset($this->iter);
    }

    /**
     * @return T
     */
    public function current(): mixed {
        [$key, $value] = current($this->iter);

        // After iteration we iterate children since we are accessing it
        // through a node-name
        return new ($this->elementClass)(
            $key,
            $value,
            Varien_Simplexml_Element::ITER_CHILDREN,
        );
    }

    /**
     * @return string
     */
    public function key(): mixed {
        return current($this->iter)[0];
    }

    public function next(): void {
        next($this->iter);
    }

    public function valid(): bool {
        return key($this->iter) !== null;
    }
}
