Completed
Push — master ( 14e29f...efb36f )
by David
02:04
created

Repository   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 0 Features 2
Metric Value
wmc 6
c 2
b 0
f 2
lcom 1
cbo 3
dl 0
loc 64
ccs 0
cts 27
cp 0
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A createForType() 0 4 1
A load() 0 10 1
A save() 0 5 1
A enforceTypeConstraint() 0 6 2
1
<?php
2
3
namespace Rawkode\Eidetic\EventSourcing;
4
5
use Rawkode\Eidetic\EventStore\EventStore;
6
7
/**
8
 * Class Repository
9
 * @package Rawkode\Eidetic\EventSourcing
10
 */
11
final class Repository
12
{
13
    /** @var $entityClass */
14
    private $entityClass;
15
16
    /** @var EventStore $eventStore */
17
    private $eventStore;
18
19
    /**
20
     * @param string $class
21
     * @param EventStore $eventStore
22
     */
23
    private function __construct($class, EventStore $eventStore)
24
    {
25
        $this->entityClass = $class;
26
        $this->eventStore = $eventStore;
27
    }
28
29
    /**
30
     * @param $class
31
     * @param EventStore $eventStore
32
     * @return Repository
33
     */
34
    public static function createForType($class, EventStore $eventStore)
35
    {
36
        return new self($class, $eventStore);
37
    }
38
39
    /**
40
     * @param $key
41
     * @return mixed
42
     */
43
    public function load($key)
44
    {
45
        $class = $this->eventStore->getClassForKey($key);
46
47
        $this->enforceTypeConstraint($class);
48
49
        $events = $this->eventStore->retrieve($key);
50
51
        return $class::initialise($events);
52
    }
53
54
    /**
55
     * @param EventSourcedEntity $eventSourcedEntity
56
     * @throws IncorrectEntityClassException
57
     */
58
    public function save(EventSourcedEntity $eventSourcedEntity)
59
    {
60
        $this->enforceTypeConstraint(get_class($eventSourcedEntity));
61
        $this->eventStore->store($eventSourcedEntity->identifier(), $eventSourcedEntity->stagedEvents());
62
    }
63
64
    /**
65
     * @param $class
66
     * @throws IncorrectEntityClassException
67
     */
68
    private function enforceTypeConstraint($class)
69
    {
70
        if ($class !== $this->entityClass) {
71
            throw new IncorrectEntityClassException($class . ' is not same as ' . $this->entityClass);
72
        }
73
    }
74
}
75