index/src/ArrayIterator.php

66 lines
1.3 KiB
PHP
Raw Normal View History

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