Passed
Pull Request — master (#779)
by Gabriel
11:29
created

SqlGenerator   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 23
dl 0
loc 53
ccs 24
cts 24
cp 1
rs 10
c 0
b 0
f 0
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A generate() 0 38 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\Migrations\Generator;
6
7
use Doctrine\DBAL\Platforms\AbstractPlatform;
8
use Doctrine\Migrations\Configuration\Configuration;
9
use SqlFormatter;
10
use function array_unshift;
11
use function count;
12
use function implode;
13
use function sprintf;
14
use function stripos;
15
use function strlen;
16
use function var_export;
17
18
/**
19
 * The SqlGenerator class is responsible for generating the body of the up() and down() methods for a migration
20
 * from an array of SQL queries.
21
 *
22
 * @internal
23
 */
24
class SqlGenerator
25
{
26
    /** @var Configuration */
27
    private $configuration;
28
29
    /** @var AbstractPlatform */
30
    private $platform;
31
32 7
    public function __construct(Configuration $configuration, AbstractPlatform $platform)
33
    {
34 7
        $this->configuration = $configuration;
35 7
        $this->platform      = $platform;
36 7
    }
37
38
    /** @param string[] $sql */
39 6
    public function generate(
40
        array $sql,
41
        bool $formatted = false,
42
        int $lineLength = 120
43
    ) : string {
44 6
        $code = [];
45
46 6
        foreach ($sql as $query) {
47 6
            if (stripos($query, $this->configuration->getMigrationsTableName()) !== false) {
48 4
                continue;
49
            }
50
51 6
            if ($formatted) {
52 2
                $maxLength = $lineLength - 18 - 8; // max - php code length - indentation
53
54 2
                if (strlen($query) > $maxLength) {
55 2
                    $query = SqlFormatter::format($query, false);
56
                }
57
            }
58
59 6
            $code[] = sprintf('$this->addSql(%s);', var_export($query, true));
60
        }
61
62 6
        if (count($code) !== 0) {
63 6
            $currentPlatform = $this->platform->getName();
64
65 6
            array_unshift(
66 6
                $code,
67 6
                sprintf(
68 6
                    '$this->abortIf($this->connection->getDatabasePlatform()->getName() !== %s, %s);',
69 6
                    var_export($currentPlatform, true),
70 6
                    var_export(sprintf("Migration can only be executed safely on '%s'.", $currentPlatform), true)
71
                ),
72 6
                ''
73
            );
74
        }
75
76 6
        return implode("\n", $code);
77
    }
78
}
79