Issues (3)

src/AggregateRootBehaviour.php (1 issue)

1
<?php
2
3
declare(strict_types=1);
4
5
namespace EventSauce\EventSourcing;
6
7
use Generator;
8
9
/**
10
 * @see AggregateRoot
11
 */
12
trait AggregateRootBehaviour
13
{
14
    /**
15
     * @var AggregateRootId
16
     */
17
    private $aggregateRootId;
18
19
    /**
20
     * @var int
21
     */
22
    private $aggregateRootVersion = 0;
23
24
    /**
25
     * @var object[]
26
     */
27
    private $recordedEvents = [];
28
29 8
    public function __construct(AggregateRootId $aggregateRootId)
30
    {
31 8
        $this->aggregateRootId = $aggregateRootId;
32 8
    }
33
34 8
    public function aggregateRootId(): AggregateRootId
35
    {
36 8
        return $this->aggregateRootId;
37
    }
38
39 8
    public function aggregateRootVersion(): int
40
    {
41 8
        return $this->aggregateRootVersion;
42
    }
43
44 4
    protected function apply(object $event)
45
    {
46 4
        $parts = explode('\\', get_class($event));
47 4
        $this->{'apply' . end($parts)}($event);
48 4
        $this->aggregateRootVersion++;
49 4
    }
50
51 4
    protected function recordThat(object $event)
52
    {
53 4
        $this->apply($event);
54 4
        $this->recordedEvents[] = $event;
55 4
    }
56
57
    /**
58
     * @return object[]
59
     */
60 8
    public function releaseEvents(): array
61
    {
62 8
        $releasedEvents = $this->recordedEvents;
63 8
        $this->recordedEvents = [];
64
65 8
        return $releasedEvents;
66
    }
67
68
    /**
69
     * @param AggregateRootId $aggregateRootId
70
     * @param Generator       $events
71
     *
72
     * @return AggregateRoot
73
     * @see AggregateRoot::reconstituteFromEvents
74
     */
75 8
    public static function reconstituteFromEvents(AggregateRootId $aggregateRootId, Generator $events): AggregateRoot
76
    {
77
        /** @var AggregateRoot&AggregateRootBehaviour $aggregateRoot */
78 8
        $aggregateRoot = new static($aggregateRootId);
79
80
        /** @var object $event */
81 8
        foreach ($events as $event) {
82 2
            $aggregateRoot->apply($event);
83
        }
84
85 8
        return $aggregateRoot;
0 ignored issues
show
Bug Best Practice introduced by Frank de Jonge
The expression return $aggregateRoot returns the type EventSauce\EventSourcing\AggregateRootBehaviour which is incompatible with the type-hinted return EventSauce\EventSourcing\AggregateRoot.
Loading history...
86
    }
87
}
88