FlattenIterator::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 4
rs 10
1
<?php
2
3
namespace BenTools\FlattenIterator;
4
5
use IteratorAggregate;
6
use Traversable;
7
8
class FlattenIterator implements IteratorAggregate
9
{
10
    /**
11
     * @var iterable<iterable>
12
     */
13
    private iterable $iterables;
14
15
    private bool $preserveKeys;
16
17
    /**
18
     * @param iterable<iterable> $iterables
19
     */
20
    public function __construct(iterable $iterables, bool $preserveKeys = false)
21
    {
22
        $this->iterables = $iterables;
23
        $this->preserveKeys = $preserveKeys;
24
    }
25
26
    /**
27
     * @inheritDoc
28
     */
29
    public function getIterator(): Traversable
30
    {
31
        foreach ($this->iterables as $iterable) {
32
            if (!is_iterable($iterable)) {
33
                throw new \InvalidArgumentException('All iterables must be iterable.');
34
            }
35
            if (true === $this->preserveKeys) {
36
                foreach ($iterable as $key => $value) {
37
                    yield $key => $value;
38
                }
39
            } else {
40
                foreach ($iterable as $value) {
41
                    yield $value;
42
                }
43
            }
44
        }
45
    }
46
47
    /**
48
     * @return array|FlattenIterator
49
     */
50
    public function asArray(): array
51
    {
52
        return iterator_to_array($this);
53
    }
54
}
55