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

SqlGenerator::generate()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 38
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 6.0045

Importance

Changes 0
Metric Value
cc 6
eloc 19
nc 10
nop 3
dl 0
loc 38
ccs 19
cts 20
cp 0.95
crap 6.0045
rs 8.439
c 0
b 0
f 0
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
 * @internal
20
 */
21
class SqlGenerator
22
{
23
    /** @var Configuration */
24
    private $configuration;
25
26
    /** @var AbstractPlatform */
27
    private $platform;
28
29 7
    public function __construct(Configuration $configuration, AbstractPlatform $platform)
30
    {
31 7
        $this->configuration = $configuration;
32 7
        $this->platform      = $platform;
33 7
    }
34
35
    /** @param string[] $sql */
36 6
    public function generate(
37
        array $sql,
38
        bool $formatted = false,
39
        int $lineLength = 120
40
    ) : string {
41 6
        $code = [];
42
43 6
        foreach ($sql as $query) {
44 6
            if (stripos($query, $this->configuration->getMigrationsTableName()) !== false) {
45 4
                continue;
46
            }
47
48 6
            if ($formatted) {
49 2
                $maxLength = $lineLength - 18 - 8; // max - php code length - indentation
50
51 2
                if (strlen($query) > $maxLength) {
52 2
                    $query = SqlFormatter::format($query, false);
53
                }
54
            }
55
56 6
            $code[] = sprintf('$this->addSql(%s);', var_export($query, true));
57
        }
58
59 6
        if (count($code) !== 0) {
60 6
            $currentPlatform = $this->platform->getName();
61
62 6
            array_unshift(
63
                $code,
64 6
                sprintf(
65 6
                    '$this->abortIf($this->connection->getDatabasePlatform()->getName() !== %s, %s);',
66 6
                    var_export($currentPlatform, true),
67 6
                    var_export(sprintf("Migration can only be executed safely on '%s'.", $currentPlatform), true)
68
                ),
69 6
                ''
70
            );
71
        }
72
73 6
        return implode("\n", $code);
74
    }
75
}
76