Passed
Push — 2.x ( 927817...94cb61 )
by Aleksei
13:29
created

SingleFileStrategy::generate()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 14
nc 6
nop 2
dl 0
loc 24
rs 9.7998
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cycle\Schema\Generator\Migrations\Strategy;
6
7
use Cycle\Database\Schema\AbstractTable;
8
use Cycle\Migrations\Atomizer\Atomizer;
9
use Cycle\Migrations\Atomizer\Renderer;
10
use Cycle\Migrations\Config\MigrationConfig;
11
use Cycle\Schema\Generator\Migrations\MigrationImage;
12
use Cycle\Schema\Generator\Migrations\NameGeneratorInterface;
13
14
final class SingleFileStrategy implements GeneratorStrategyInterface
15
{
16
    private static int $sec = 0;
17
18
    public function __construct(
19
        private readonly MigrationConfig $migrationConfig,
20
        private readonly NameGeneratorInterface $nameGenerator
21
    ) {
22
    }
23
24
    /**
25
     * @param non-empty-string $database
0 ignored issues
show
Documentation Bug introduced by
The doc comment non-empty-string at position 0 could not be parsed: Unknown type name 'non-empty-string' at position 0 in non-empty-string.
Loading history...
26
     * @param array<AbstractTable> $tables
27
     *
28
     * @return array<MigrationImage>
29
     */
30
    public function generate(string $database, array $tables): array
31
    {
32
        $atomizer = new Atomizer(new Renderer());
33
34
        $reasonable = false;
35
        foreach ($tables as $table) {
36
            if ($table->getComparator()->hasChanges()) {
37
                $reasonable = true;
38
                $atomizer->addTable($table);
39
            }
40
        }
41
42
        if (!$reasonable) {
43
            return [];
44
        }
45
46
        $image = new MigrationImage($this->migrationConfig, $database);
47
        $image->setName($this->nameGenerator->generate($atomizer));
48
        $image->fileNamePattern = self::$sec++ . '_{database}_{name}';
49
50
        $atomizer->declareChanges($image->getClass()->getMethod('up'));
51
        $atomizer->revertChanges($image->getClass()->getMethod('down'));
52
53
        return [$image];
54
    }
55
}
56