AggregateRootEventRecorder   A
last analyzed

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