-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
SimpleCachingIteratorAggregate.php
59 lines (50 loc) · 1.4 KB
/
SimpleCachingIteratorAggregate.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
declare(strict_types=1);
namespace loophp\iterators;
use CachingIterator;
use Generator;
use Iterator;
use IteratorAggregate;
/**
* @template TKey
* @template T
*
* @implements IteratorAggregate<array-key|TKey, T>
*
* This iterator must be used only if keys are int|string. When it is used with
* keys of different type, during the first loop keys are ok, but during the
* next loops, keys are replaced by integers.
* This is mostly due to the fact that the method
* CachingIterator::getCache returns an array, and keys of an array can only be
* int|string.
* In order to circumvent that, use CachingIteratorAggregate instead.
*/
final class SimpleCachingIteratorAggregate implements IteratorAggregate
{
private CachingIterator $iterator;
/**
* @param Iterator<TKey, T> $iterator
*/
public function __construct(Iterator $iterator)
{
$this->iterator = new CachingIterator(
$iterator,
CachingIterator::FULL_CACHE
);
}
/**
* @return Generator<array-key|TKey, T>
*/
public function getIterator(): Generator
{
yield from $this->iterator->getCache();
while ($this->iterator->hasNext()) {
$this->iterator->next();
yield $this->iterator->key() => $this->iterator->current();
}
}
public function hasNext(): bool
{
return $this->iterator->hasNext();
}
}