1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Skobkin\Bundle\PointToolsBundle\EventListener; |
4
|
|
|
|
5
|
|
|
use Doctrine\Common\EventSubscriber; |
6
|
|
|
// For new doctrine: https://symfony.com/doc/current/cookbook/doctrine/event_listeners_subscribers.html#creating-the-subscriber-class |
7
|
|
|
//use Doctrine\Common\Persistence\Event\LifecycleEventArgs; |
8
|
|
|
//use Doctrine\Common\Persistence\Event\PreUpdateEventArgs; |
9
|
|
|
use Doctrine\ORM\Event\PostFlushEventArgs; |
10
|
|
|
use Doctrine\ORM\Event\PreUpdateEventArgs; |
11
|
|
|
use Skobkin\Bundle\PointToolsBundle\Entity\User; |
12
|
|
|
use Skobkin\Bundle\PointToolsBundle\Entity\UserRenameEvent; |
13
|
|
|
use Skobkin\Bundle\PointToolsBundle\Event\UsersRenamedEvent; |
14
|
|
|
use Symfony\Component\EventDispatcher\EventDispatcherInterface; |
15
|
|
|
|
16
|
|
|
class UsersUpdatedSubscriber implements EventSubscriber |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* @var UserRenameEvent[] |
20
|
|
|
*/ |
21
|
|
|
private $renames = []; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @var EventDispatcherInterface |
25
|
|
|
*/ |
26
|
|
|
private $eventDispatcher; |
27
|
|
|
|
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* UserRenameSubscriber constructor. |
31
|
|
|
* |
32
|
|
|
* @param EventDispatcherInterface $eventDispatcher |
33
|
|
|
*/ |
34
|
14 |
|
public function __construct(EventDispatcherInterface $eventDispatcher) |
35
|
|
|
{ |
36
|
14 |
|
$this->eventDispatcher = $eventDispatcher; |
37
|
14 |
|
} |
38
|
|
|
|
39
|
14 |
|
public function getSubscribedEvents(): array |
40
|
|
|
{ |
41
|
|
|
return [ |
42
|
14 |
|
'preUpdate', |
43
|
|
|
'postFlush', |
44
|
|
|
]; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
public function preUpdate(PreUpdateEventArgs $event): void |
48
|
|
|
{ |
49
|
|
|
/** @var User $entity */ |
50
|
|
|
$entity = $event->getObject(); |
51
|
|
|
|
52
|
|
|
if (!$entity instanceof User) { |
53
|
|
|
return; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
if ($event->hasChangedField('login')) { |
57
|
|
|
$this->renames[] = new UserRenameEvent($entity, $event->getOldValue('login')); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
public function postFlush(PostFlushEventArgs $event): void |
62
|
|
|
{ |
63
|
|
|
if (0 !== count($this->renames)) { |
64
|
|
|
// Creating event for dispatch |
65
|
|
|
$usersRenamedEvent = new UsersRenamedEvent($this->renames); |
66
|
|
|
|
67
|
|
|
$em = $event->getEntityManager(); |
68
|
|
|
|
69
|
|
|
foreach ($this->renames as $item) { |
70
|
|
|
$em->persist($item); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
$this->renames = []; |
74
|
|
|
|
75
|
|
|
$em->flush(); |
76
|
|
|
|
77
|
|
|
$this->eventDispatcher->dispatch(UsersRenamedEvent::NAME, $usersRenamedEvent); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
} |