Skip to content

Commit 74e0150

Browse files
committed
added Iterables::toIterator()
1 parent 326431b commit 74e0150

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

src/Utils/Iterables.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,4 +156,21 @@ public static function map(iterable $iterable, callable $transformer): \Generato
156156
yield $k => $transformer($v, $k, $iterable);
157157
}
158158
}
159+
160+
161+
/**
162+
* Creates an iterator from anything that is iterable.
163+
* @template K
164+
* @template V
165+
* @param iterable<K, V> $iterable
166+
* @return \Iterator<K, V>
167+
*/
168+
public static function toIterator(iterable $iterable): \Iterator
169+
{
170+
return match (true) {
171+
$iterable instanceof \Iterator => $iterable,
172+
$iterable instanceof \IteratorAggregate => self::toIterator($iterable->getIterator()),
173+
is_array($iterable) => new \ArrayIterator($iterable),
174+
};
175+
}
159176
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
<?php
2+
3+
/**
4+
* Test: Nette\Utils\Iterables::toIterator()
5+
*/
6+
7+
declare(strict_types=1);
8+
9+
use Nette\Utils\Iterables;
10+
use Tester\Assert;
11+
12+
require __DIR__ . '/../bootstrap.php';
13+
14+
15+
test('array', function () {
16+
$arr = ['Nette', 'Framework'];
17+
$tmp = [];
18+
foreach (Iterables::toIterator($arr) as $k => $v) {
19+
$tmp[] = "$k => $v";
20+
}
21+
22+
Assert::same([
23+
'0 => Nette',
24+
'1 => Framework',
25+
], $tmp);
26+
});
27+
28+
29+
test('Iterator', function () {
30+
$arr = new ArrayIterator(['Nette', 'Framework']);
31+
$tmp = [];
32+
foreach (Iterables::toIterator($arr) as $k => $v) {
33+
$tmp[] = "$k => $v";
34+
}
35+
36+
Assert::same([
37+
'0 => Nette',
38+
'1 => Framework',
39+
], $tmp);
40+
});
41+
42+
43+
test('IteratorAggregate', function () {
44+
$arr = new ArrayObject(['Nette', 'Framework']);
45+
Assert::type(ArrayIterator::class, Iterables::toIterator($arr));
46+
47+
$tmp = [];
48+
foreach (Iterables::toIterator($arr) as $k => $v) {
49+
$tmp[] = "$k => $v";
50+
}
51+
52+
Assert::same([
53+
'0 => Nette',
54+
'1 => Framework',
55+
], $tmp);
56+
});

0 commit comments

Comments
 (0)