Completed
Push — master ( 566f81...189392 )
by Olivier
03:22
created

Loader::getGroups()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Shapin\Datagen\DBAL;
6
7
use Doctrine\DBAL\Schema\Schema;
8
9
class Loader
10
{
11
    private $tables = [];
12
    private $groups = [];
13
14 2
    public function addTable(Table $table, array $groups = []): void
15
    {
16 2
        $this->tables[$table->getTableName()] = $table;
17
18 2
        foreach ($groups as $group) {
19
            if (!isset($this->groups[$group])) {
20
                $this->groups[$group] = [];
21
            }
22
            $this->groups[$group][] = $table->getTableName();
23
        }
24 2
    }
25
26 3
    public function getSchema(array $groups = []): Schema
27
    {
28 3
        $schema = new Schema();
29
30 3
        foreach ($this->getTables($groups) as $table) {
31 1
            $table->addTableToSchema($schema);
32
        }
33
34 3
        return $schema;
35
    }
36
37 3
    public function getFixtures(array $groups = []): iterable
38
    {
39 3
        foreach ($this->getTables($groups) as $table) {
40 1
            $tableName = $table->getTableName();
41 1
            $types = $table->getTypes();
42
43 1
            foreach ($table->getRows() as $row) {
44 1
                yield [$tableName, $row, $types];
45
            }
46
        }
47 3
    }
48
49 3
    public function getGroups(): array
50
    {
51 3
        return array_keys($this->groups);
52
    }
53
54 5
    private function getTables(array $groups = []): array
55
    {
56
        // Check that all groups exists.
57 5
        foreach ($groups as $group) {
58
            if (!isset($this->groups[$group])) {
59
                throw new \InvalidArgumentException(sprintf('Unknown group %s. Available: [%s]', $group, implode(', ', array_keys($this->groups))));
60
            }
61
        }
62
63 5
        if (0 === count($groups)) {
64 5
            $tables = $this->tables;
65
        } else {
66
            $tables = [];
67
            foreach ($groups as $group) {
68
                foreach ($this->groups[$group] as $tableInGroup) {
69
                    $tables[] = $this->tables[$tableInGroup];
70
                }
71
            }
72
        }
73
74
        // Order all tables
75 5
        usort($tables, function ($a, $b) {
76 2
            if ($a->getOrder() === $b->getOrder()) {
77 2
                return 0;
78
            }
79
80 2
            return $a->getOrder() < $b->getOrder() ? -1 : 1;
81 5
        });
82
83 5
        return $tables;
84
    }
85
}
86