Passed
Push — main ( 3a55e4...eef38b )
by Pol
11:53
created

UniqueIterableAggregate::getIterator()   A

Complexity

Conditions 4
Paths 4

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 4
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
use Traversable;
15
16
use function in_array;
17
18
use const PHP_INT_MAX;
19
20
/**
21
 * @template TKey
22
 * @template T
23
 *
24
 * @implements IteratorAggregate<TKey, T>
25
 */
26
final class UniqueIterableAggregate implements IteratorAggregate
27
{
28
    /**
29
     * @var iterable<TKey, T>
30
     */
31
    private iterable $iterable;
32
33
    private int $retries;
34
35
    /**
36
     * @param iterable<TKey, T> $iterable
37
     */
38 1
    public function __construct(iterable $iterable, int $retries = PHP_INT_MAX)
39
    {
40 1
        $this->iterable = $iterable;
41 1
        $this->retries = $retries;
42
    }
43
44
    /**
45
     * @return Generator<TKey, T>
46
     */
47 1
    public function getIterator(): Traversable
48
    {
49 1
        $retries = $this->retries;
50 1
        $seen = [];
51
52 1
        foreach ($this->iterable as $key => $value) {
53 1
            if (0 === $retries) {
54 1
                break;
55
            }
56
57 1
            if (in_array($value, $seen, true)) {
58 1
                --$retries;
59
60 1
                continue;
61
            }
62
63 1
            $seen[] = $value;
64
65 1
            yield $key => $value;
66
        }
67
    }
68
}
69