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