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