CartesianIterator::setFlags()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Enjoys\CartesianIterator;
6
7
use Iterator;
8
use MultipleIterator;
9
10
final class CartesianIterator extends MultipleIterator
11
{
12
    /** @var Iterator[] */
13
    private $iterators = [];
14
15
    /** @var int */
16
    private $info = 0;
17
18
    /**
19
     * @param int $flags
20
     * @psalm-suppress ArgumentTypeCoercion
21
     */
22 7
    public function __construct($flags = MultipleIterator::MIT_KEYS_ASSOC)
23
    {
24 7
        parent::__construct($flags  | MultipleIterator::MIT_NEED_ALL);
25
    }
26
27
    /**
28
     * @param int $flags
29
     * @return void
30
     * @psalm-suppress ArgumentTypeCoercion
31
     */
32 2
    public function setFlags($flags): void
33
    {
34 2
        parent::setFlags($flags | MultipleIterator::MIT_NEED_ALL);
35
    }
36
37
    /**
38
     * @param Iterator $iterator
39
     * @param int|null|string $info
40
     * @return void
41
     */
42 7
    public function attachIterator(Iterator $iterator, $info = null): void
43
    {
44 7
        $this->iterators[] = $iterator;
45 7
        parent::attachIterator($iterator, $info ?? $this->info++);
46
    }
47
48 2
    public function detachIterator(Iterator $iterator): void
49
    {
50 2
        if (!$this->containsIterator($iterator)) {
51 1
            return;
52
        }
53
54 1
        parent::detachIterator($iterator);
55
56 1
        $key = array_search($iterator, $this->iterators, true);
57 1
        unset($this->iterators[$key]);
58
59 1
        $this->iterators = array_values($this->iterators);
60
    }
61
62 5
    public function next(int $index = 0): void
63
    {
64 5
        $iterator = $this->iterators[$index++];
65 5
        $iterator->next();
66 5
        if (!$iterator->valid() && $index < $this->countIterators()) {
67 5
            $iterator->rewind();
68 5
            $this->next($index);
69
        }
70
    }
71
72 5
    public function toArray(): array
73
    {
74 5
        $result = [];
75 5
        foreach ($this as $item) {
76 5
            $result[] = $item;
77
        }
78 5
        return $result;
79
    }
80
81
}