index/src/ArrayIterator.php

65 lines
1.3 KiB
PHP

<?php
// ArrayIterator.php
// Created: 2022-02-03
// Updated: 2024-08-03
namespace Index;
use Iterator;
/**
* Provides an Iterator implementation for normal arrays.
*
* @implements Iterator<mixed, mixed>
*/
class ArrayIterator implements Iterator {
private bool $wasValid = true;
/**
* @param array<mixed, mixed> $array Array to iterate upon.
*/
public function __construct(
private array $array
) {}
/**
* Returns the current element.
*
* @return mixed Can return any type.
*/
public function current(): mixed {
return current($this->array);
}
/**
* Returns the key of the current element.
*
* @return mixed Returns scalar on success, or null on failure.
*/
public function key(): mixed {
return key($this->array);
}
/**
* Moves forward to next element.
*/
public function next(): void {
$this->wasValid = next($this->array) !== false;
}
/**
* Rewind the Iterator to the first element.
*/
public function rewind(): void {
$this->wasValid = reset($this->array) !== false;
}
/**
* Checks if current position is valid.
*
* @return bool Returns true on success or false on failure.
*/
public function valid(): bool {
return $this->wasValid;
}
}