-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEventSourcedEntity.php
86 lines (72 loc) · 1.84 KB
/
EventSourcedEntity.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
/*
* This file is part of the broadway/broadway package.
*
* (c) Qandidate.com <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Broadway\EventSourcing;
/**
* Convenience base class for event sourced entities.
*/
abstract class EventSourcedEntity implements EventSourcedEntityInterface
{
/**
* @var EventSourcedAggregateRoot|null
*/
private $aggregateRoot;
/**
* {@inheritDoc}
*/
public function handleRecursively($event)
{
$this->handle($event);
foreach ($this->getChildEntities() as $entity) {
$entity->registerAggregateRoot($this->aggregateRoot);
$entity->handleRecursively($event);
}
}
/**
* {@inheritDoc}
*/
public function registerAggregateRoot(EventSourcedAggregateRoot $aggregateRoot)
{
if (null !== $this->aggregateRoot && $this->aggregateRoot !== $aggregateRoot) {
throw new AggregateRootAlreadyRegisteredException();
}
$this->aggregateRoot = $aggregateRoot;
}
protected function apply($event)
{
$this->aggregateRoot->apply($event);
}
/**
* Handles event if capable.
*
* @param $event
*/
protected function handle($event)
{
$method = $this->getApplyMethod($event);
if (! method_exists($this, $method)) {
return;
}
$this->$method($event);
}
/**
* Returns all child entities
*
* @return EventSourcedEntityInterface[]
*/
protected function getChildEntities()
{
return [];
}
private function getApplyMethod($event)
{
$classParts = explode('\\', get_class($event));
return 'apply' . end($classParts);
}
}