1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Knp\RadBundle\DomainEvent\Dispatcher; |
4
|
|
|
|
5
|
|
|
use Symfony\Component\EventDispatcher\EventDispatcherInterface; |
6
|
|
|
use Doctrine\ORM\Event\LifecycleEventArgs; |
7
|
|
|
use Doctrine\ORM\Event\PostFlushEventArgs; |
8
|
|
|
use Knp\RadBundle\DomainEvent\Provider; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Uses doctrine postFlush event, |
12
|
|
|
* to loop over all entities that implement the "Provider" interface, |
13
|
|
|
* and dipatches all the events using a symfony event dispatcher |
14
|
|
|
* It's important to use postFlush to ensure everything is saved correctly (transaction commited) |
15
|
|
|
* before doing extra stuff (like sending emails f.e). |
16
|
|
|
**/ |
17
|
|
|
class Doctrine |
18
|
|
|
{ |
19
|
|
|
protected $dispatcher; |
20
|
|
|
protected $entities = []; |
21
|
|
|
|
22
|
|
|
public function __construct(EventDispatcherInterface $dispatcher) |
23
|
|
|
{ |
24
|
|
|
$this->dispatcher = $dispatcher; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public function postPersist(LifecycleEventArgs $event) |
28
|
|
|
{ |
29
|
|
|
$this->keepProvider($event); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function postUpdate(LifecycleEventArgs $event) |
33
|
|
|
{ |
34
|
|
|
$this->keepProvider($event); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function postRemove(LifecycleEventArgs $event) |
38
|
|
|
{ |
39
|
|
|
$this->keepProvider($event); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
public function postFlush(PostFlushEventArgs $event) |
|
|
|
|
43
|
|
|
{ |
44
|
|
|
foreach ($this->entities as $entity) { |
45
|
|
|
foreach ($entity->popEvents() as $event) { |
46
|
|
|
$event->setSubject($entity); |
47
|
|
|
$this->dispatcher->dispatch($event->getName(), $event); |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
private function keepProvider(LifecycleEventArgs $event) |
53
|
|
|
{ |
54
|
|
|
$entity = $event->getEntity(); |
55
|
|
|
|
56
|
|
|
if (!$entity instanceof Provider) { |
57
|
|
|
return; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
$this->entities[] = $entity; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
This check looks from parameters that have been defined for a function or method, but which are not used in the method body.