|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Avoran\RapidoAdapter\DoctrineDbalStorage; |
|
4
|
|
|
|
|
5
|
|
|
use Doctrine\DBAL\Connection; |
|
6
|
|
|
use Doctrine\DBAL\Exception\UniqueConstraintViolationException; |
|
7
|
|
|
use Avoran\Rapido\ReadModel\ReadModelConfiguration; |
|
8
|
|
|
use Avoran\Rapido\ReadModel\ReadModelField; |
|
9
|
|
|
use Avoran\Rapido\ReadModel\StorageWriter; |
|
10
|
|
|
|
|
11
|
|
|
class DoctrineDbalStorageWriter implements StorageWriter |
|
12
|
|
|
{ |
|
13
|
|
|
private $connection; |
|
14
|
|
|
private $checkedSchema = []; |
|
15
|
|
|
private $schemaSynchronizer; |
|
16
|
|
|
private $tableNameGenerator; |
|
17
|
|
|
private $idColumnName; |
|
18
|
|
|
private $dbalTypeMapper; |
|
19
|
|
|
|
|
20
|
|
|
public function __construct |
|
21
|
|
|
( |
|
22
|
|
|
Connection $connection, |
|
23
|
|
|
SchemaSynchronizer $tableGenerator, |
|
24
|
|
|
NameGenerator $tableNameGenerator, |
|
25
|
|
|
$idColumnName, |
|
26
|
|
|
DbalTypeMapper $dbalTypeMapper |
|
27
|
|
|
) |
|
28
|
|
|
{ |
|
29
|
|
|
$this->connection = $connection; |
|
30
|
|
|
$this->schemaSynchronizer = $tableGenerator; |
|
31
|
|
|
$this->tableNameGenerator = $tableNameGenerator; |
|
32
|
|
|
$this->idColumnName = $idColumnName; |
|
33
|
|
|
$this->dbalTypeMapper = $dbalTypeMapper; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
public function writeRecord(ReadModelConfiguration $metadata, $recordData) |
|
37
|
|
|
{ |
|
38
|
|
|
if (!isset($this->checkedSchema[$metadata->getName()])) { |
|
39
|
|
|
$this->schemaSynchronizer->ensureTableExists($metadata); |
|
40
|
|
|
$this->checkedSchema[$metadata->getName()] = true; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
$tableName = $this->tableNameGenerator->generate($metadata->getName()); |
|
44
|
|
|
$record = $metadata->createRecord($recordData); |
|
45
|
|
|
|
|
46
|
|
|
$types = array_map(function (ReadModelField $field) { |
|
47
|
|
|
return $this->dbalTypeMapper->mapReadModelToDbalType($field->getDataType()); |
|
48
|
|
|
}, $metadata->getFields()); |
|
49
|
|
|
|
|
50
|
|
|
$rowData = array_merge([$this->idColumnName => $record->getId()], $record->getData()); |
|
51
|
|
|
$idType = $this->dbalTypeMapper->mapReadModelToDbalType($metadata->getId()->getDataType()); |
|
52
|
|
|
|
|
53
|
|
|
try { |
|
54
|
|
|
$this->connection->insert($tableName, $rowData, array_merge([$idType], $types)); |
|
55
|
|
|
} catch (UniqueConstraintViolationException $e) { |
|
56
|
|
|
$this->connection->update($tableName, $record->getData(), [$this->idColumnName => $record->getId()], $types); |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|