UniqueIterableAggregate::getIterator()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 10
c 1
b 0
f 0
nc 5
nop 0
dl 0
loc 19
ccs 11
cts 11
cp 1
crap 4
rs 9.9332
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 Generator;
13
use IteratorAggregate;
14
15
use function in_array;
16
17
use const PHP_INT_MAX;
18
19
/**
20
 * @template TKey
21
 * @template T
22
 *
23
 * @implements IteratorAggregate<TKey, T>
24
 */
25
final class UniqueIterableAggregate implements IteratorAggregate
26
{
27
    /**
28
     * @var InterruptableIterableIteratorAggregate<TKey, T>
29
     */
30
    private InterruptableIterableIteratorAggregate $iterable;
31
32
    /**
33
     * @param iterable<TKey, T> $iterable
34
     */
35 1
    public function __construct(iterable $iterable, private int $retries = PHP_INT_MAX)
36
    {
37 1
        $this->iterable = new InterruptableIterableIteratorAggregate($iterable);
38
    }
39
40
    /**
41
     * @return Generator<TKey, T>
42
     */
43 1
    public function getIterator(): Generator
44
    {
45 1
        $retries = $this->retries;
46 1
        $seen = [];
47
48 1
        foreach ($this->iterable as $generator => [$key, $value]) {
49 1
            if (0 === $retries) {
50 1
                $generator->send(InterruptableIterableIteratorAggregate::BREAK);
51
            }
52
53 1
            if (in_array($value, $seen, true)) {
54 1
                --$retries;
55
56 1
                continue;
57
            }
58
59 1
            $seen[] = $value;
60
61 1
            yield $key => $value;
62
        }
63
    }
64
}
65