Completed
Push — master ( b28f87...a255d6 )
by Olivier
03:32
created

Processor::getName()   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\Connection;
8
use Doctrine\DBAL\Schema\Schema;
9
use Shapin\Datagen\FixtureInterface;
10
use Shapin\Datagen\ProcessorInterface;
11
12
class Processor implements ProcessorInterface
13
{
14
    private $connection;
15
    private $schema;
16
17
    private $fixturesToLoad = [];
18
19 5
    public function __construct(Connection $connection)
20
    {
21 5
        $this->connection = $connection;
22 5
        $this->schema = new Schema();
23 5
    }
24
25
    /**
26
     * {@inheritdoc}
27
     */
28 5
    public function process(FixtureInterface $fixture, array $options = []): void
29
    {
30 5
        if (!$fixture instanceof TableInterface) {
31
            return;
32
        }
33
34 5
        if (!$this->resolveOption($options, 'fixtures_only', false)) {
35 4
            $fixture->addTableToSchema($this->schema);
36
        }
37
38 5
        if (!$this->resolveOption($options, 'schema_only', false)) {
39 4
            $this->fixturesToLoad[] = $fixture;
40
        }
41 5
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46 5
    public function flush(array $options = []): void
47
    {
48 5
        if (!$this->resolveOption($options, 'fixtures_only', false)) {
49 4
            $statements = $this->schema->toSql($this->connection->getDatabasePlatform());
50 4
            foreach ($statements as $statement) {
51 4
                $this->connection->query($statement);
52
            }
53
54
            // Reset schema
55 4
            $this->schema = new Schema();
56
        }
57
58 5
        if (!$this->resolveOption($options, 'schema_only', false)) {
59 4
            foreach ($this->fixturesToLoad as $fixture) {
60 4
                $tableName = $fixture->getTableName();
61 4
                $types = $fixture->getTypes();
62
63 4
                foreach ($fixture->getRows() as $row) {
64 4
                    $this->connection->insert($tableName, $row, $types);
65
                }
66
            }
67
        }
68 5
    }
69
70
    /**
71
     * {@inheritdoc}
72
     */
73 2
    public function getName(): string
74
    {
75 2
        return 'dbal';
76
    }
77
78 5
    private function resolveOption(array $options, string $key, $defaultValue = null)
79
    {
80 5
        if (!array_key_exists($key, $options)) {
81 3
            return $defaultValue;
82
        }
83
84 4
        return $options[$key];
85
    }
86
}
87