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