-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEntity.php
More file actions
87 lines (76 loc) · 2.11 KB
/
Entity.php
File metadata and controls
87 lines (76 loc) · 2.11 KB
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
87
<?php namespace SmoothPhp\EventSourcing;
use SmoothPhp\Contracts\EventSourcing\Event;
use SmoothPhp\Contracts\EventSourcing\AggregateRoot as AggregateRootContract;
/**
* Abstract class Entity
*
* @author jrdn hannah <jrdn@jrdnhannah.co.uk>
*/
abstract class Entity implements \SmoothPhp\Contracts\EventSourcing\Entity
{
/** @var AggregateRootContract */
private $aggregateRoot;
/**
* @param Event $event
* @throws Exception\AggregateRootAlreadyRegistered
*/
public function handleRecursively(Event $event)
{
$this->handle($event);
foreach ($this->getChildren() as $entity) {
$entity->registerAggregateRoot($this->aggregateRoot);
$entity->handleRecursively($event);
}
}
/**
* @param AggregateRootContract $aggregateRoot
* @throws Exception\AggregateRootAlreadyRegistered
*/
public function registerAggregateRoot(AggregateRootContract $aggregateRoot)
{
if (null !== $this->aggregateRoot && $this->aggregateRoot !== $aggregateRoot) {
throw new Exception\AggregateRootAlreadyRegistered;
}
$this->aggregateRoot = $aggregateRoot;
}
/**
* @return \SmoothPhp\Contracts\EventSourcing\Entity[] $entity
*/
public function getChildren()
{
return [];
}
/**
* @param Event $event
* @throws Exception\NoAggregateRootRegistered
*/
protected function apply(Event $event)
{
if (!$this->aggregateRoot) {
throw new Exception\NoAggregateRootRegistered;
}
$this->aggregateRoot->apply($event);
}
/**
* Handles event if capable.
*
* @param $event
*/
protected function handle(Event $event)
{
$method = $this->getApplyMethod($event);
if (!method_exists($this, $method)) {
return;
}
$this->$method($event);
}
/**
* @param Event $event
* @return string
*/
private function getApplyMethod(Event $event)
{
$classParts = explode('\\', get_class($event));
return 'apply' . end($classParts);
}
}