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
|
|
|
|