-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathBatchProfileProjector.php
More file actions
96 lines (81 loc) · 2.62 KB
/
Copy pathBatchProfileProjector.php
File metadata and controls
96 lines (81 loc) · 2.62 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
86
87
88
89
90
91
92
93
94
95
96
<?php
declare(strict_types=1);
namespace Patchlevel\EventSourcing\Tests\Benchmark\BasicImplementation\Projection;
use Doctrine\DBAL\Connection;
use Patchlevel\EventSourcing\Attribute\Projector;
use Patchlevel\EventSourcing\Attribute\Setup;
use Patchlevel\EventSourcing\Attribute\Subscribe;
use Patchlevel\EventSourcing\Attribute\Teardown;
use Patchlevel\EventSourcing\Subscription\Subscriber\BatchableSubscriber;
use Patchlevel\EventSourcing\Subscription\Subscriber\SubscriberUtil;
use Patchlevel\EventSourcing\Tests\Benchmark\BasicImplementation\Events\NameChanged;
use Patchlevel\EventSourcing\Tests\Benchmark\BasicImplementation\Events\ProfileCreated;
#[Projector('profile')]
final class BatchProfileProjector implements BatchableSubscriber
{
use SubscriberUtil;
/** @var array<string, string> */
private array $nameChanged = [];
public function __construct(
private Connection $connection,
) {
}
#[Setup]
public function create(): void
{
$this->connection->executeStatement("CREATE TABLE IF NOT EXISTS {$this->table()} (id VARCHAR PRIMARY KEY, name VARCHAR);");
}
#[Teardown]
public function drop(): void
{
$this->connection->executeStatement("DROP TABLE IF EXISTS {$this->table()};");
}
#[Subscribe(ProfileCreated::class)]
public function onProfileCreated(ProfileCreated $profileCreated): void
{
$this->connection->insert(
$this->table(),
[
'id' => $profileCreated->profileId->toString(),
'name' => $profileCreated->name,
],
);
}
#[Subscribe(NameChanged::class)]
public function onNameChanged(NameChanged $nameChanged): void
{
$this->nameChanged[$nameChanged->profileId->toString()] = $nameChanged->name;
}
public function table(): string
{
return 'projection_' . $this->subscriberId();
}
public function beginBatch(): void
{
$this->nameChanged = [];
}
public function commitBatch(): void
{
try {
$this->connection->transactional(function (): void {
foreach ($this->nameChanged as $profileId => $name) {
$this->connection->update(
$this->table(),
['name' => $name],
['id' => $profileId],
);
}
});
} finally {
$this->nameChanged = [];
}
}
public function rollbackBatch(): void
{
$this->nameChanged = [];
}
public function forceCommit(): bool
{
return false;
}
}