-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAggregateRootBehavior.php
More file actions
80 lines (64 loc) · 2.16 KB
/
Copy pathAggregateRootBehavior.php
File metadata and controls
80 lines (64 loc) · 2.16 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
<?php
declare(strict_types=1);
namespace TinyBlocks\BuildingBlocks\Aggregate;
use Ramsey\Uuid\Uuid;
use ReflectionClass;
use TinyBlocks\BuildingBlocks\Entity\EntityBehavior;
use TinyBlocks\BuildingBlocks\Event\DomainEvent;
use TinyBlocks\BuildingBlocks\Event\EventRecord;
use TinyBlocks\BuildingBlocks\Event\EventRecords;
use TinyBlocks\BuildingBlocks\Event\EventType;
use TinyBlocks\BuildingBlocks\Event\SequenceNumber;
use TinyBlocks\BuildingBlocks\Snapshot\SnapshotData;
use TinyBlocks\Time\Instant;
trait AggregateRootBehavior
{
use EntityBehavior;
private EventRecords $recordedEvents;
private SequenceNumber $sequenceNumber;
public function sequenceNumber(): SequenceNumber
{
return $this->sequenceNumber ?? SequenceNumber::initial();
}
public function modelVersion(): ModelVersion
{
return ModelVersion::initial();
}
public function aggregateName(): string
{
return new ReflectionClass(objectOrClass: static::class)->getShortName();
}
protected function nextSequenceNumber(): void
{
$this->sequenceNumber = $this->sequenceNumber()->next();
}
protected function generateSnapshotData(): SnapshotData
{
return new SnapshotData(payload: $this->snapshotState());
}
protected function snapshotState(): array
{
$state = get_object_vars($this);
unset($state['recordedEvents'], $state['sequenceNumber']);
return $state;
}
public function recordedEvents(): EventRecords
{
$records = $this->recordedEvents ?? EventRecords::createFromEmpty();
return EventRecords::createFrom(elements: $records);
}
protected function buildEventRecord(DomainEvent $event): EventRecord
{
return new EventRecord(
id: Uuid::uuid4(),
type: EventType::fromEvent(event: $event),
event: $event,
identity: $this->identity(),
revision: $event->revision(),
occurredOn: Instant::now(),
snapshotData: $this->generateSnapshotData(),
aggregateType: $this->aggregateName(),
sequenceNumber: $this->sequenceNumber()
);
}
}