mediawiki-extensions-Echo/includes/iterator/MultipleIterator.php
Mark A. Hershberger 43d004fc3d
Make interface compatible with RecursiveIterator
Seen when running phpunit tests.

Bug: T289879
Change-Id: I6f05b2cf21cd7c51b6d3234e6e0356c8a563202a
2022-07-09 22:48:39 -04:00

73 lines
1.6 KiB
PHP

<?php
/**
* Presents a list of iterators as a single stream of results
* when wrapped with the RecursiveIteratorIterator.
*
* This differs from the SPL MultipleIterator in the following ways:
* * Does not return null for non-valid child iterators
* * implements RecursiveIterator
* * Lots less features(e.g. simple!)
*/
class EchoMultipleIterator implements RecursiveIterator {
/** @var Iterator[] */
protected $active = [];
/** @var array */
protected $children;
/** @var int */
protected $key = 0;
public function __construct( array $children ) {
$this->children = $children;
}
public function rewind(): void {
$this->active = $this->children;
$this->key = 0;
foreach ( $this->active as $key => $it ) {
$it->rewind();
if ( !$it->valid() ) {
unset( $this->active[$key] );
}
}
}
public function valid(): bool {
return (bool)$this->active;
}
public function next(): void {
$this->key++;
foreach ( $this->active as $key => $it ) {
$it->next();
if ( !$it->valid() ) {
unset( $this->active[$key] );
}
}
}
#[\ReturnTypeWillChange]
public function current() {
$result = [];
foreach ( $this->active as $it ) {
$result[] = $it->current();
}
return $result;
}
public function key(): int {
return $this->key;
}
public function hasChildren(): bool {
return (bool)$this->active;
}
public function getChildren(): ?RecursiveIterator {
// The NotRecursiveIterator is used rather than a RecursiveArrayIterator
// so that nested arrays dont get recursed.
return new EchoNotRecursiveIterator( new ArrayIterator( $this->current() ) );
}
}