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
|
5 |
|
public function __construct(EventBus $bus, $enable) |
37
|
|
|
{ |
38
|
5 |
|
$this->bus = $bus; |
39
|
5 |
|
$this->enable = $enable; |
40
|
5 |
|
} |
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
|
3 |
|
public function postFlush(PostFlushEventArgs $args) |
60
|
|
|
{ |
61
|
3 |
|
$map = $args->getEntityManager()->getUnitOfWork()->getIdentityMap(); |
62
|
|
|
|
63
|
|
|
// flush only if has domain events |
64
|
|
|
// it necessary for fix recursive handle flush |
65
|
3 |
|
if ($this->publish($map)) { |
66
|
1 |
|
$args->getEntityManager()->flush(); |
67
|
|
|
} |
68
|
3 |
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* @param array $map |
72
|
|
|
* |
73
|
|
|
* @return bool |
74
|
|
|
*/ |
75
|
3 |
|
private function publish(array $map) |
76
|
|
|
{ |
77
|
3 |
|
$has_events = false; |
78
|
3 |
|
foreach ($map as $entities) { |
79
|
2 |
|
foreach ($entities as $entity) { |
80
|
|
|
// ignore Doctrine proxy classes |
81
|
|
|
// proxy class can't have a domain events |
82
|
2 |
|
if ($entity instanceof Proxy || !($entity instanceof AggregateEvents)) { |
83
|
1 |
|
break; |
84
|
|
|
} |
85
|
|
|
|
86
|
2 |
|
foreach ($entity->pullEvents() as $event) { |
87
|
1 |
|
$this->bus->publish($event); |
88
|
2 |
|
$has_events = true; |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|
93
|
3 |
|
return $has_events; |
94
|
|
|
} |
95
|
|
|
} |
96
|
|
|
|