Failed Conditions
Pull Request — master (#707)
by Jonathan
03:12
created

FileBuilder::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 4
dl 0
loc 10
ccs 5
cts 5
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\Migrations\Generator;
6
7
use DateTimeInterface;
8
use Doctrine\DBAL\Platforms\AbstractPlatform;
9
use Doctrine\Migrations\Version\Direction;
10
use function sprintf;
11
12
/**
13
 * @internal
14
 */
15
final class FileBuilder
16
{
17
    /** @var AbstractPlatform */
18
    private $platform;
19
20
    /** @var string */
21
    private $tableName;
22
23
    /** @var string */
24
    private $columnName;
25
26
    /** @var string */
27
    private $executedAtColumnName;
28
29 9
    public function __construct(
30
        AbstractPlatform $platform,
31
        string $tableName,
32
        string $columnName,
33
        string $executedAtColumnName
34
    ) {
35 9
        $this->platform             = $platform;
36 9
        $this->tableName            = $tableName;
37 9
        $this->columnName           = $columnName;
38 9
        $this->executedAtColumnName = $executedAtColumnName;
39 9
    }
40
41
    /** @param string[][] $queriesByVersion */
42 8
    public function buildMigrationFile(
43
        array $queriesByVersion,
44
        string $direction,
45
        DateTimeInterface $now
46
    ) : string {
47 8
        $string = sprintf("-- Doctrine Migration File Generated on %s\n", $now->format('Y-m-d H:i:s'));
48
49 8
        foreach ($queriesByVersion as $version => $queries) {
50 8
            $version = (string) $version;
51
52 8
            $string .= "\n-- Version " . $version . "\n";
53
54 8
            foreach ($queries as $query) {
55 8
                $string .= $query . ";\n";
56
            }
57
58 8
            $string .= $this->getVersionUpdateQuery($version, $direction);
59
        }
60
61 8
        return $string;
62
    }
63
64 8
    private function getVersionUpdateQuery(string $version, string $direction) : string
65
    {
66 8
        if ($direction === Direction::DOWN) {
67 3
            return sprintf(
68 3
                "DELETE FROM %s WHERE %s = '%s';\n",
69 3
                $this->tableName,
70 3
                $this->columnName,
71 3
                $version
72
            );
73
        }
74
75 5
        return sprintf(
76 5
            "INSERT INTO %s (%s, %s) VALUES ('%s', %s);\n",
77 5
            $this->tableName,
78 5
            $this->columnName,
79 5
            $this->executedAtColumnName,
80 5
            $version,
81 5
            $this->platform->getCurrentTimestampSQL()
82
        );
83
    }
84
}
85