Completed
Push — master ( 8dd935...0e2bba )
by Peter
04:33
created

DomainEventPublisher   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 11
lcom 2
cbo 4
dl 0
loc 70
ccs 23
cts 23
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getSubscribedEvents() 0 10 2
C postFlush() 0 30 8
1
<?php
2
3
/**
4
 * GpsLab component.
5
 *
6
 * @author    Peter Gribanov <[email protected]>
7
 * @copyright Copyright (c) 2011, Peter Gribanov
8
 * @license   http://opensource.org/licenses/MIT
9
 */
10
11
namespace GpsLab\Bundle\DomainEvent\Event\Listener;
12
13
use Doctrine\Common\EventSubscriber;
14
use Doctrine\Common\Persistence\Proxy;
15
use Doctrine\ORM\Event\PostFlushEventArgs;
16
use Doctrine\ORM\Events;
17
use GpsLab\Domain\Event\Aggregator\AggregateEvents;
18
use GpsLab\Domain\Event\Bus\EventBus;
19
20
class DomainEventPublisher implements EventSubscriber
21
{
22
    /**
23
     * @var EventBus
24
     */
25
    private $bus;
26
27
    /**
28
     * @var bool
29
     */
30
    private $enable;
31
32
    /**
33
     * @param EventBus $bus
34
     * @param bool     $enable
35
     */
36 6
    public function __construct(EventBus $bus, $enable)
37
    {
38 6
        $this->bus = $bus;
39 6
        $this->enable = $enable;
40 6
    }
41
42
    /**
43
     * @return array
44
     */
45 2
    public function getSubscribedEvents()
46
    {
47 2
        if (!$this->enable) {
48 1
            return [];
49
        }
50
51
        return [
52 1
            Events::postFlush,
53
        ];
54
    }
55
56
    /**
57
     * @param PostFlushEventArgs $args
58
     */
59 4
    public function postFlush(PostFlushEventArgs $args)
60
    {
61 4
        $em = $args->getEntityManager();
62
63 4
        if ($em->isOpen()) {
64 3
            $map = $em->getUnitOfWork()->getIdentityMap();
65 3
            $has_events = false;
66
67 3
            foreach ($map as $entities) {
68 2
                foreach ($entities as $entity) {
69
                    // ignore Doctrine proxy classes
70
                    // proxy class can't have a domain events
71 2
                    if ($entity instanceof Proxy || !($entity instanceof AggregateEvents)) {
72 1
                        break;
73
                    }
74
75 2
                    foreach ($entity->pullEvents() as $event) {
76 1
                        $this->bus->publish($event);
77 2
                        $has_events = true;
78
                    }
79
                }
80
            }
81
82
            // flush only if has domain events
83
            // it necessary for fix recursive handle flush
84 3
            if ($has_events) {
85 1
                $em->flush();
86
            }
87
        }
88 4
    }
89
}
90