Completed
Pull Request — master (#178)
by Beñat
03:05
created

AggregateRootEventRecorder   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 56
c 0
b 0
f 0
wmc 10
lcom 1
cbo 2
rs 10

8 Methods

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