Issues (14)

src/Snapshotting/SnapshottingBehaviour.php (1 issue)

1
<?php
2
3
declare(strict_types=1);
4
5
namespace EventSauce\EventSourcing\Snapshotting;
6
7
use EventSauce\EventSourcing\AggregateRoot;
8
use EventSauce\EventSourcing\AggregateRootId;
9
use Generator;
10
11
trait SnapshottingBehaviour
12
{
13
    /**
14
     * @var positive-int|0
0 ignored issues
show
Documentation Bug introduced by
The doc comment positive-int|0 at position 0 could not be parsed: Unknown type name 'positive-int' at position 0 in positive-int|0.
Loading history...
15
     */
16
    private int $aggregateRootVersion = 0;
17
18
    abstract public function aggregateRootVersion(): int;
19
20
    abstract public function aggregateRootId(): AggregateRootId;
21
22
    abstract protected function apply(object $event): void;
23
24 1
    public function createSnapshot(): Snapshot
25
    {
26 1
        return new Snapshot($this->aggregateRootId(), $this->aggregateRootVersion(), $this->createSnapshotState());
27
    }
28
29
    abstract protected function createSnapshotState(): mixed;
30
31
    public static function reconstituteFromSnapshotAndEvents(Snapshot $snapshot, Generator $events): static
32
    {
33
        $id = $snapshot->aggregateRootId();
34 1
        /** @var static&AggregateRoot $aggregateRoot */
35
        $aggregateRoot = static::reconstituteFromSnapshotState($id, $snapshot->state());
36 1
        $aggregateRoot->aggregateRootVersion = $snapshot->aggregateRootVersion();
37
38 1
        foreach ($events as $event) {
39 1
            $aggregateRoot->apply($event);
40
        }
41 1
42 1
        $aggregateRoot->aggregateRootVersion = $events->getReturn() ?: $aggregateRoot->aggregateRootVersion;
43
44
        return $aggregateRoot;
45 1
    }
46
47 1
    abstract protected static function reconstituteFromSnapshotState(AggregateRootId $id, $state): AggregateRootWithSnapshotting;
48
}
49