2022-09-13 13:13:11 +00:00
|
|
|
<?php
|
|
|
|
// ArrayIterator.php
|
|
|
|
// Created: 2022-02-03
|
2023-11-09 13:12:34 +00:00
|
|
|
// Updated: 2023-11-09
|
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.
|
|
|
|
*/
|
2022-09-13 13:13:11 +00:00
|
|
|
class ArrayIterator implements Iterator {
|
|
|
|
private array $array;
|
|
|
|
private bool $wasValid = true;
|
|
|
|
|
2023-11-09 13:12:34 +00:00
|
|
|
/**
|
|
|
|
* @param array $array Array to iterate upon.
|
|
|
|
*/
|
2022-09-13 13:13:11 +00:00
|
|
|
public function __construct(array $array) {
|
|
|
|
$this->array = $array;
|
|
|
|
}
|
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
}
|