Passed
Push — main ( 405102...8e59d9 )
by Pol
04:53
created

CachingIteratorAggregate::getIterator()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 8
rs 10
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 Iterator;
14
use IteratorAggregate;
15
use Traversable;
16
17
/**
18
 * @template TKey
19
 * @template T
20
 *
21
 * @implements IteratorAggregate<TKey, T>
22
 */
23
final class CachingIteratorAggregate implements IteratorAggregate
24
{
25
    /**
26
     * @var CachingIterator<TKey, T>
27
     */
28
    private CachingIterator $cache;
29
30
    /**
31
     * @var Iterator<TKey, T>
32
     */
33
    private Iterator $iterator;
34
35
    /**
36
     * @param Iterator<TKey, T> $iterator
37
     */
38
    public function __construct(Iterator $iterator)
39
    {
40
        $this->iterator = $iterator;
41
        $this->cache = new CachingIterator(
42
            (new PackIterableAggregate($iterator))->getIterator(),
43
            CachingIterator::FULL_CACHE
44
        );
45
    }
46
47
    /**
48
     * @return Traversable<TKey, T>
49
     */
50
    public function getIterator(): Traversable
51
    {
52
        /** @var iterable<int, array{0: TKey, 1: T}> $it */
53
        $it = $this->iterator->valid()
54
            ? $this->cache
55
            : $this->cache->getCache();
56
57
        yield from (new UnpackIterableAggregate($it))->getIterator();
58
    }
59
}
60