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

AggregateRootRepository   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 5
dl 0
loc 55
ccs 21
cts 21
cp 1
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 2
A retrieve() 0 8 1
A retrieveAllEvents() 0 7 2
A persist() 0 4 1
A persistEvents() 0 8 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
}