Skip to content

Commit

Permalink
added Iterables::toIterator()
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Jun 18, 2024
1 parent 460138f commit 6310f42
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/Utils/Iterables.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<K, V> $iterable
* @return \Iterator<K, V>
*/
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),
};
}
}
56 changes: 56 additions & 0 deletions tests/Utils/Iterables.toIterator().phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

/**
* Test: Nette\Utils\Iterables::toIterator()
*/

declare(strict_types=1);

use Nette\Utils\Iterables;
use Tester\Assert;

require __DIR__ . '/../bootstrap.php';


test('array', function () {
$arr = ['Nette', 'Framework'];
$tmp = [];
foreach (Iterables::toIterator($arr) as $k => $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);
});

0 comments on commit 6310f42

Please sign in to comment.