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
|
|
|
* @param non-empty-string $database |
|
|
|
|
25
|
|
|
* @param array<AbstractTable> $tables |
26
|
|
|
* |
27
|
|
|
* @return array<MigrationImage> |
28
|
|
|
*/ |
29
|
|
|
public function generate(string $database, array $tables): array |
30
|
|
|
{ |
31
|
|
|
$atomizer = new Atomizer(new Renderer()); |
32
|
|
|
|
33
|
|
|
$reasonable = false; |
34
|
|
|
foreach ($tables as $table) { |
35
|
|
|
if ($table->getComparator()->hasChanges()) { |
36
|
|
|
$reasonable = true; |
37
|
|
|
$atomizer->addTable($table); |
38
|
|
|
} |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
if (!$reasonable) { |
42
|
|
|
return []; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
$image = new MigrationImage($this->migrationConfig, $database); |
46
|
|
|
$image->setName($this->nameGenerator->generate($atomizer)); |
47
|
|
|
$image->fileNamePattern = self::$sec++ . '_{database}_{name}'; |
48
|
|
|
|
49
|
|
|
$atomizer->declareChanges($image->getClass()->getMethod('up')); |
50
|
|
|
$atomizer->revertChanges($image->getClass()->getMethod('down')); |
51
|
|
|
|
52
|
|
|
return [$image]; |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|