SimpleRepository   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 3
eloc 16
c 1
b 0
f 0
dl 0
loc 30
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A save() 0 5 1
A load() 0 5 1
1
<?php declare(strict_types=1);
2
namespace Kepawni\Twilted\Basic;
3
4
use Assert\Assert;
5
use Kepawni\Twilted\EntityHistory;
6
use Kepawni\Twilted\EntityIdentifier;
7
use Kepawni\Twilted\EventBus;
8
use Kepawni\Twilted\EventSourcedEntity;
9
use Kepawni\Twilted\EventStore;
10
use Kepawni\Twilted\IdentifiableEventSourcedEntity;
11
use Kepawni\Twilted\Repository;
12
13
class SimpleRepository implements Repository
14
{
15
    /** @var string|EventSourcedEntity */
16
    private $entityClass;
17
    private $eventBus;
18
    private $eventStore;
19
    /** @var string|EntityHistory */
20
    private $historyClass;
21
22
    public function __construct(string $entityClass, EventBus $eventBus, EventStore $eventStore, string $historyClass = SimpleAggregateHistory::class)
23
    {
24
        Assert::that($entityClass)->implementsInterface(EventSourcedEntity::class);
25
        $this->entityClass = $entityClass;
26
        $this->eventBus = $eventBus;
27
        $this->eventStore = $eventStore;
28
        $this->historyClass = $historyClass;
29
    }
30
31
    public function load(EntityIdentifier $identifier): EventSourcedEntity
32
    {
33
        $eventStream = $this->eventStore->retrieve($identifier);
34
        $aggregateHistory = new $this->historyClass($identifier, $eventStream);
35
        return $this->entityClass::reconstituteFrom($aggregateHistory);
36
    }
37
38
    public function save(IdentifiableEventSourcedEntity $entity): void
39
    {
40
        $eventStream = $entity->getRecordedEvents();
41
        $this->eventStore->append($eventStream);
42
        $this->eventBus->dispatch($eventStream);
43
    }
44
}
45