Completed
Pull Request — master (#39)
by
unknown
02:32 queued 24s
created

Repository   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 0%

Importance

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

5 Methods

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