diff --git a/src/Utils/Iterables.php b/src/Utils/Iterables.php index a2a0b53e..e64f8f13 100644 --- a/src/Utils/Iterables.php +++ b/src/Utils/Iterables.php @@ -156,4 +156,21 @@ public static function map(iterable $iterable, callable $transformer): \Generato yield $k => $transformer($v, $k, $iterable); } } + + + /** + * Creates an iterator from anything that is iterable. + * @template K + * @template V + * @param iterable $iterable + * @return \Iterator + */ + public static function toIterator(iterable $iterable): \Iterator + { + return match (true) { + $iterable instanceof \Iterator => $iterable, + $iterable instanceof \IteratorAggregate => self::toIterator($iterable->getIterator()), + is_array($iterable) => new \ArrayIterator($iterable), + }; + } } diff --git a/tests/Utils/Iterables.toIterator().phpt b/tests/Utils/Iterables.toIterator().phpt new file mode 100644 index 00000000..1b92bef7 --- /dev/null +++ b/tests/Utils/Iterables.toIterator().phpt @@ -0,0 +1,56 @@ + $v) { + $tmp[] = "$k => $v"; + } + + Assert::same([ + '0 => Nette', + '1 => Framework', + ], $tmp); +}); + + +test('Iterator', function () { + $arr = new ArrayIterator(['Nette', 'Framework']); + $tmp = []; + foreach (Iterables::toIterator($arr) as $k => $v) { + $tmp[] = "$k => $v"; + } + + Assert::same([ + '0 => Nette', + '1 => Framework', + ], $tmp); +}); + + +test('IteratorAggregate', function () { + $arr = new ArrayObject(['Nette', 'Framework']); + Assert::type(ArrayIterator::class, Iterables::toIterator($arr)); + + $tmp = []; + foreach (Iterables::toIterator($arr) as $k => $v) { + $tmp[] = "$k => $v"; + } + + Assert::same([ + '0 => Nette', + '1 => Framework', + ], $tmp); +});