1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Shared Kernel library. |
5
|
|
|
* |
6
|
|
|
* Copyright (c) 2016-present LIN3S <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace LIN3S\SharedKernel\Infrastructure\Event\SimpleBus\EventRecorder\Doctrine\ORM; |
15
|
|
|
|
16
|
|
|
use Doctrine\Common\EventSubscriber; |
17
|
|
|
use Doctrine\ORM\Event\LifecycleEventArgs; |
18
|
|
|
use Doctrine\ORM\Events; |
19
|
|
|
use LIN3S\SharedKernel\Domain\Model\AggregateRoot; |
20
|
|
|
use SimpleBus\Message\Recorder\ContainsRecordedMessages; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @author Beñat Espiña <[email protected]> |
24
|
|
|
*/ |
25
|
|
|
class AggregateRootEventRecorder implements EventSubscriber, ContainsRecordedMessages |
26
|
|
|
{ |
27
|
|
|
private $collectedEvents; |
28
|
|
|
|
29
|
|
|
public function __construct() |
30
|
|
|
{ |
31
|
|
|
$this->collectedEvents = []; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function getSubscribedEvents() : array |
35
|
|
|
{ |
36
|
|
|
return [ |
37
|
|
|
Events::postPersist, |
38
|
|
|
Events::postUpdate, |
39
|
|
|
Events::postRemove, |
40
|
|
|
]; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
public function postPersist(LifecycleEventArgs $event) : void |
44
|
|
|
{ |
45
|
|
|
$this->collectEventsFromAggregateRoot($event); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
public function postUpdate(LifecycleEventArgs $event) : void |
49
|
|
|
{ |
50
|
|
|
$this->collectEventsFromAggregateRoot($event); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
public function postRemove(LifecycleEventArgs $event) : void |
54
|
|
|
{ |
55
|
|
|
$this->collectEventsFromAggregateRoot($event); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
public function recordedMessages() : array |
59
|
|
|
{ |
60
|
|
|
return $this->collectedEvents; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
public function eraseMessages() : void |
64
|
|
|
{ |
65
|
|
|
$this->collectedEvents = []; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
private function collectEventsFromAggregateRoot(LifecycleEventArgs $event) : void |
69
|
|
|
{ |
70
|
|
|
$entity = $event->getEntity(); |
71
|
|
|
|
72
|
|
|
if ($entity instanceof AggregateRoot) { |
73
|
|
|
foreach ($entity->recordedEvents() as $event) { |
74
|
|
|
$this->collectedEvents[] = $event; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
$entity->clearEvents(); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|