1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Silverback\ApiComponentBundle\EventSubscriber; |
4
|
|
|
|
5
|
|
|
use Doctrine\Common\EventSubscriber; |
6
|
|
|
use Doctrine\ORM\Event\LifecycleEventArgs; |
7
|
|
|
use Doctrine\ORM\Event\OnFlushEventArgs; |
8
|
|
|
use Doctrine\ORM\Event\PreFlushEventArgs; |
9
|
|
|
use Doctrine\ORM\Event\PreUpdateEventArgs; |
10
|
|
|
use Doctrine\ORM\Events; |
11
|
|
|
use Silverback\ApiComponentBundle\EventSubscriber\EntitySubscriber\EntitySubscriberInterface; |
12
|
|
|
|
13
|
|
|
class DoctrineSubscriber implements EventSubscriber |
14
|
|
|
{ |
15
|
|
|
/** @var iterable|EntitySubscriberInterface[] */ |
16
|
|
|
private $entitySubscribers; |
17
|
|
|
|
18
|
|
|
public function __construct(iterable $entitySubscribers) |
19
|
|
|
{ |
20
|
|
|
$this->entitySubscribers = $entitySubscribers; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
public function getSubscribedEvents(): array |
24
|
|
|
{ |
25
|
|
|
return [ |
26
|
|
|
Events::prePersist, |
27
|
|
|
Events::preUpdate, |
28
|
|
|
Events::preFlush, |
29
|
|
|
Events::onFlush, |
30
|
|
|
Events::preRemove |
31
|
|
|
]; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function prePersist(LifecycleEventArgs $args): void |
35
|
|
|
{ |
36
|
|
|
$this->runEntitySubscribers($args, Events::prePersist); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function preUpdate(LifecycleEventArgs $args): void |
40
|
|
|
{ |
41
|
|
|
$this->runEntitySubscribers($args, Events::preUpdate); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
public function preFlush(PreFlushEventArgs $args): void |
45
|
|
|
{ |
46
|
|
|
$this->runEntitySubscribers($args, Events::preFlush); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
public function onFlush(OnFlushEventArgs $args): void |
50
|
|
|
{ |
51
|
|
|
$this->runEntitySubscribers($args, Events::onFlush); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function preRemove(LifecycleEventArgs $args): void |
55
|
|
|
{ |
56
|
|
|
$this->runEntitySubscribers($args, Events::preRemove); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
private function runEntitySubscribers($args, string $event): void |
60
|
|
|
{ |
61
|
|
|
$entity = ($args instanceof LifecycleEventArgs || $args instanceof PreUpdateEventArgs) ? $args->getEntity() : null; |
62
|
|
|
foreach ($this->entitySubscribers as $entitySubscriber) { |
63
|
|
|
$subscribedEvents = $entitySubscriber->getSubscribedEvents(); |
64
|
|
|
if ($entitySubscriber->supportsEntity($entity)) { |
65
|
|
|
if (in_array($event, $subscribedEvents, true)) { |
66
|
|
|
$entitySubscriber->$event($args, $entity); |
67
|
|
|
} |
68
|
|
|
if (array_key_exists($event, $subscribedEvents)) { |
69
|
|
|
$fn = $subscribedEvents[$event]; |
70
|
|
|
$entitySubscriber->$fn($args, $entity); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|