-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathDoctrineStatefulSubscriberStore.php
More file actions
85 lines (69 loc) · 2.59 KB
/
Copy pathDoctrineStatefulSubscriberStore.php
File metadata and controls
85 lines (69 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php
declare(strict_types=1);
namespace Patchlevel\EventSourcing\Subscription\StatefulSubscriber;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Types\Types;
use Patchlevel\EventSourcing\Metadata\Subscriber\AttributeSubscriberMetadataFactory;
use Patchlevel\EventSourcing\Metadata\Subscriber\SubscriberMetadataFactory;
use Patchlevel\EventSourcing\Schema\DoctrineHelper;
use Patchlevel\EventSourcing\Schema\DoctrineSchemaConfigurator;
use Patchlevel\Hydrator\HydratorWithContext;
use Patchlevel\Hydrator\MetadataHydrator;
use function json_decode;
use function json_encode;
final readonly class DoctrineStatefulSubscriberStore implements StatefulSubscriberStore, DoctrineSchemaConfigurator
{
public function __construct(
private Connection $connection,
private HydratorWithContext $hydrator = new MetadataHydrator(),
private SubscriberMetadataFactory $subscriberMetadataFactory = new AttributeSubscriberMetadataFactory(),
private string $tableName = 'stateful_subscriber_state',
) {
}
public function store(StatefulSubscriber $subscriber): void
{
$subscriberId = $this->subscriberId($subscriber);
$data = $this->hydrator->extract($subscriber);
$this->connection->insert(
$this->tableName,
[
'id' => $subscriberId,
'state' => json_encode($data),
],
);
}
public function load(StatefulSubscriber $subscriber): void
{
$subscriberId = $this->subscriberId($subscriber);
$data = $this->connection->fetchAssociative(
'SELECT * FROM ' . $this->tableName . ' WHERE id = ?',
[$subscriberId],
);
if (!$data) {
return;
}
$this->hydrator->hydrate(
$subscriber::class,
json_decode($data['state'], true),
[HydratorWithContext::OBJECT_TO_POPULATE => $subscriber],
);
}
public function configureSchema(Schema $schema, Connection $connection): void
{
if (!DoctrineHelper::sameDatabase($this->connection, $connection)) {
return;
}
$table = $schema->createTable($this->tableName);
$table->addColumn('id', Types::STRING)
->setLength(255)
->setNotnull(true);
$table->addColumn('state', Types::JSON)
->setNotnull(true);
$table->setPrimaryKey(['id']);
}
public function subscriberId(StatefulSubscriber $projection): string
{
return $this->subscriberMetadataFactory->metadata($projection::class)->id;
}
}