1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Cycle\Schema\Generator\Migrations; |
6
|
|
|
|
7
|
|
|
use Cycle\Schema\Generator\Migrations\Exception\GeneratorException; |
8
|
|
|
use Cycle\Schema\Generator\Migrations\Strategy\GeneratorStrategyInterface; |
9
|
|
|
use Cycle\Schema\Generator\Migrations\Strategy\SingleFileStrategy; |
10
|
|
|
use Cycle\Schema\Generator\SyncTables; |
11
|
|
|
use Cycle\Schema\GeneratorInterface; |
12
|
|
|
use Cycle\Schema\Registry; |
13
|
|
|
use Cycle\Database\Schema\AbstractTable; |
14
|
|
|
use Cycle\Migrations\Config\MigrationConfig; |
15
|
|
|
use Cycle\Migrations\RepositoryInterface; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Migration generator creates set of migrations needed to sync database schema with desired state. Each database will |
19
|
|
|
* receive it's own migration. |
20
|
|
|
*/ |
21
|
|
|
class GenerateMigrations implements GeneratorInterface |
22
|
|
|
{ |
23
|
|
|
private GeneratorStrategyInterface $strategy; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param MigrationConfig $migrationConfig deprecated param since v2.2.0. |
27
|
|
|
*/ |
28
|
|
|
public function __construct( |
29
|
|
|
private RepositoryInterface $repository, |
30
|
|
|
private MigrationConfig $migrationConfig, |
31
|
|
|
?GeneratorStrategyInterface $strategy = null, |
32
|
|
|
) { |
33
|
|
|
$this->strategy = $strategy ?? new SingleFileStrategy($migrationConfig, new NameBasedOnChangesGenerator()); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public function run(Registry $registry): Registry |
37
|
|
|
{ |
38
|
|
|
$databases = []; |
39
|
|
|
foreach ($registry as $e) { |
40
|
|
|
if ($registry->hasTable($e) && !$e->getOptions()->has(SyncTables::READONLY_SCHEMA)) { |
41
|
|
|
$databases[$registry->getDatabase($e)][] = $registry->getTableSchema($e); |
42
|
|
|
} |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
foreach ($databases as $database => $tables) { |
46
|
|
|
foreach ($this->strategy->generate($database, $tables) as $image) { |
47
|
|
|
$class = $image->getClass()->getName(); |
48
|
|
|
$name = \substr($image->buildFileName(), 0, 128); |
49
|
|
|
|
50
|
|
|
$this->repository->registerMigration($name, $class, (string) $image->getFile()); |
|
|
|
|
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
return $registry; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @param AbstractTable[] $tables |
59
|
|
|
* |
60
|
|
|
* @return array [string, FileDeclaration] |
61
|
|
|
* |
62
|
|
|
* @deprecated since v2.2.0 |
63
|
|
|
*/ |
64
|
|
|
protected function generate(string $database, array $tables): ?MigrationImage |
65
|
|
|
{ |
66
|
|
|
if (!$this->strategy instanceof SingleFileStrategy) { |
67
|
|
|
throw new GeneratorException('Only `SingleFileStrategy` is supported.'); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
$images = $this->strategy->generate($database, $tables); |
71
|
|
|
|
72
|
|
|
return \array_shift($images); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|