1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Avoran\RapidoAdapter\DoctrineDbalStorage; |
4
|
|
|
|
5
|
|
|
use Doctrine\DBAL\Schema\AbstractSchemaManager; |
6
|
|
|
use Doctrine\DBAL\Schema\Comparator; |
7
|
|
|
use Doctrine\DBAL\Schema\Table; |
8
|
|
|
use Avoran\Rapido\ReadModel\ReadModelConfiguration; |
9
|
|
|
use Avoran\Rapido\ReadModel\ReadModelField; |
10
|
|
|
|
11
|
|
|
class SchemaSynchronizer |
12
|
|
|
{ |
13
|
|
|
private $schemaManager; |
14
|
|
|
private $schemaComparator; |
15
|
|
|
private $tableNameGenerator; |
16
|
|
|
private $idColumnName; |
17
|
|
|
private $columnFactory; |
18
|
|
|
|
19
|
|
|
public function __construct |
20
|
|
|
( |
21
|
|
|
AbstractSchemaManager $schemaManager, |
22
|
|
|
Comparator $schemaComparator, |
23
|
|
|
NameGenerator $tableNameGenerator, |
24
|
|
|
$idColumnName, |
25
|
|
|
ColumnFactory $columnFactory |
26
|
|
|
) |
27
|
|
|
{ |
28
|
|
|
$this->schemaManager = $schemaManager; |
29
|
|
|
$this->schemaComparator = $schemaComparator; |
30
|
|
|
$this->tableNameGenerator = $tableNameGenerator; |
31
|
|
|
$this->idColumnName = $idColumnName; |
32
|
|
|
$this->columnFactory = $columnFactory; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public function ensureTableExists(ReadModelConfiguration $metadata) |
36
|
|
|
{ |
37
|
|
|
$targetTable = new Table( |
38
|
|
|
$this->tableNameGenerator->generate($metadata->getName()), |
39
|
|
|
array_merge([$this->columnFactory->createColumn($metadata->getId()->getDataType(), $this->idColumnName)], |
40
|
|
|
array_map(function(ReadModelField $field) { |
41
|
|
|
return $this->columnFactory->createColumn($field->getDataType(), $field->getId()); |
42
|
|
|
}, $metadata->getFields()) |
43
|
|
|
) |
44
|
|
|
); |
45
|
|
|
$targetTable->setPrimaryKey([$this->idColumnName]); |
46
|
|
|
|
47
|
|
|
$existingTables = array_filter( |
48
|
|
|
$this->schemaManager->listTables(), |
49
|
|
|
function(Table $existingTable) use ($targetTable) { return $targetTable->getName() == $existingTable->getName(); } |
50
|
|
|
); |
51
|
|
|
|
52
|
|
|
if (count($existingTables) > 1) |
53
|
|
|
throw new \UnexpectedValueException(sprintf("Multiple tables with the name '%s' exist.", $targetTable->getName())); |
54
|
|
|
|
55
|
|
|
if (count($existingTables) == 1) { |
56
|
|
|
$tableDiff = $this->schemaComparator->diffTable(current($existingTables), $targetTable); |
57
|
|
|
if ($tableDiff) |
58
|
|
|
$this->schemaManager->alterTable($tableDiff); |
|
|
|
|
59
|
|
|
} else { |
60
|
|
|
$this->schemaManager->createTable($targetTable); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|