Completed
Push — master ( 4803b3...959101 )
by Frank
03:46
created

AggregateRootRepository::persistEvents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 1
crap 1
1
<?php
2
3
namespace EventSauce\EventSourcing;
4
5
use Generator;
6
7
final class AggregateRootRepository
8
{
9
    /**
10
     * @var string
11
     */
12
    private $aggregateRootClassName;
13
14
    /**
15
     * @var MessageRepository
16
     */
17
    private $repository;
18
19
    /**
20
     * @var MessageDecorator
21
     */
22
    private $decorator;
23
24 6
    public function __construct(string $aggregateRootClassName, MessageRepository $messageRepository, MessageDecorator $decorator = null)
25
    {
26 6
        $this->aggregateRootClassName = $aggregateRootClassName;
27 6
        $this->repository = $messageRepository;
28 6
        $this->decorator = $decorator ?: new DelegatingMessageDecorator();
29 6
    }
30
31 6
    public function retrieve(AggregateRootId $aggregateRootId): AggregateRoot
32
    {
33
        /** @var AggregateRoot $className */
34 6
        $className = $this->aggregateRootClassName;
35 6
        $events = $this->retrieveAllEvents($aggregateRootId);
36
37 6
        return $className::reconstituteFromEvents($aggregateRootId, $events);
38
    }
39
40 6
    private function retrieveAllEvents(AggregateRootId $aggregateRootId): Generator
41
    {
42
        /** @var Message $message */
43 6
        foreach ($this->repository->retrieveAll($aggregateRootId) as $message) {
44 1
            yield $message->event();
45
        }
46 6
    }
47
48 6
    public function persist(AggregateRoot $aggregateRoot)
49
    {
50 6
        $this->persistEvents(...$aggregateRoot->releaseEvents());
51 6
    }
52
53
    public function persistEvents(Event ... $events)
54
    {
55 6
        $messages = array_map(function (Event $event) {
56 2
            return $this->decorator->decorate(new Message($event));
57 6
        }, $events);
58
59 6
        $this->repository->persist(... $messages);
60
    }
61
}