ArrayProvider::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 6
rs 10
c 0
b 0
f 0
ccs 5
cts 5
cp 1
crap 1
1
<?php
2
declare(strict_types=1);
3
4
namespace SlayerBirden\DataFlow\Provider;
5
6
use SlayerBirden\DataFlow\Data\SimpleBag;
7
use SlayerBirden\DataFlow\DataBagInterface;
8
use SlayerBirden\DataFlow\IdentificationTrait;
9
use SlayerBirden\DataFlow\ProviderInterface;
10
11
class ArrayProvider implements ProviderInterface
12
{
13
    use IdentificationTrait;
14
15
    private $data = [];
16
    /**
17
     * @var string
18
     */
19
    private $identifier;
20
21 6
    public function __construct(string $id, array $data)
22
    {
23 6
        $this->validate($data);
24 4
        $this->data = $data;
25 4
        $this->identifier = $id;
26 4
    }
27
28
    /**
29
     * @param array $data
30
     * @throws InvalidDataException
31
     */
32 6
    private function validate(array $data)
33
    {
34 6
        foreach ($data as $key => $row) {
35 6
            if (!is_array($row)) {
36 1
                throw new InvalidDataException(sprintf('Row #(%s) is not an array.', $key));
37
            }
38 5
            $localKeys = array_keys($row);
39 5
            sort($localKeys);
40 5
            if (isset($keys)) {
41 5
                if ($keys !== $localKeys) {
42 1
                    throw new InvalidDataException(
43 1
                        sprintf('Row #(%s) has different structure than the 1st element.', $key)
44
                    );
45
                }
46
            }
47 5
            $keys = $localKeys;
48
        }
49 4
    }
50
51
    /**
52
     * @inheritdoc
53
     */
54 3
    public function getCask(): \Generator
55
    {
56 3
        foreach ($this->data as $row) {
57 3
            yield new SimpleBag($row);
58
        }
59 3
    }
60
61
    /**
62
     * @inheritdoc
63
     */
64 1
    public function getEstimatedSize(): int
65
    {
66 1
        return count($this->data);
67
    }
68
}
69