81 lines
1.8 KiB
PHP
81 lines
1.8 KiB
PHP
<?php
|
|
// StringIterator.php
|
|
// Created: 2022-02-02
|
|
// Updated: 2022-02-02
|
|
|
|
namespace Index;
|
|
|
|
use Iterator;
|
|
|
|
/**
|
|
* Provides an iterator for IString types.
|
|
*/
|
|
class StringIterator implements Iterator {
|
|
private IString $value;
|
|
private int $length;
|
|
private int $index = 0;
|
|
private bool $wasValid = false;
|
|
|
|
/**
|
|
* Creates the iterator.
|
|
*
|
|
* @param IString $string String to iterate.
|
|
*/
|
|
public function __construct(IString $string) {
|
|
$this->value = $string;
|
|
$this->length = $string->getLength();
|
|
}
|
|
|
|
/**
|
|
* Returns the current character.
|
|
*
|
|
* @see https://www.php.net/manual/en/iterator.current.php
|
|
* @return mixed Current character.
|
|
*/
|
|
public function current(): mixed {
|
|
return $this->value[$this->index];
|
|
}
|
|
|
|
/**
|
|
* Returns the index of the current character.
|
|
*
|
|
* @see https://www.php.net/manual/en/iterator.key.php
|
|
* @return int Index of the current character.
|
|
*/
|
|
public function key(): mixed {
|
|
return $this->index;
|
|
}
|
|
|
|
/**
|
|
* Move forward to the next character.
|
|
*
|
|
* @see https://www.php.net/manual/en/iterator.next.php
|
|
*/
|
|
public function next(): void {
|
|
$next = $this->index + 1;
|
|
$this->wasValid = $next < $this->length;
|
|
|
|
if($this->wasValid)
|
|
$this->index = $next;
|
|
}
|
|
|
|
/**
|
|
* Rewind to the first character.
|
|
*
|
|
* @see https://www.php.net/manual/en/iterator.rewind.php
|
|
*/
|
|
public function rewind(): void {
|
|
$this->index = 0;
|
|
$this->wasValid = true;
|
|
}
|
|
|
|
/**
|
|
* Checks if the current index is valid.
|
|
*
|
|
* @see https://www.php.net/manual/en/iterator.rewind.php
|
|
* @return bool Whether the current index is valid.
|
|
*/
|
|
public function valid(): bool {
|
|
return $this->wasValid;
|
|
}
|
|
}
|