|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the EOffice project. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Anthonius Munthi <https://itstoni.com> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
9
|
|
|
* file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
declare(strict_types=1); |
|
13
|
|
|
|
|
14
|
|
|
namespace EOffice\User\Listener; |
|
15
|
|
|
|
|
16
|
|
|
use Doctrine\Bundle\DoctrineBundle\EventSubscriber\EventSubscriberInterface; |
|
17
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
|
18
|
|
|
use Doctrine\ORM\Events; |
|
19
|
|
|
use Doctrine\Persistence\Event\LifecycleEventArgs; |
|
20
|
|
|
use EOffice\Contracts\User\Model\UserInterface; |
|
21
|
|
|
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface; |
|
22
|
|
|
|
|
23
|
|
|
class UserListener implements EventSubscriberInterface |
|
24
|
|
|
{ |
|
25
|
|
|
private UserPasswordHasherInterface $hasher; |
|
26
|
|
|
|
|
27
|
|
|
public function __construct(UserPasswordHasherInterface $hasher) |
|
28
|
|
|
{ |
|
29
|
|
|
$this->hasher = $hasher; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* {@inheritDoc} |
|
34
|
|
|
*/ |
|
35
|
|
|
public function getSubscribedEvents(): array |
|
36
|
|
|
{ |
|
37
|
|
|
return [ |
|
38
|
|
|
Events::prePersist, |
|
39
|
|
|
Events::preUpdate, |
|
40
|
|
|
]; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
public function prePersist(LifecycleEventArgs $args) |
|
44
|
|
|
{ |
|
45
|
|
|
$object = $args->getObject(); |
|
46
|
|
|
if ($object instanceof UserInterface) { |
|
47
|
|
|
$this->updateUserFields($object); |
|
48
|
|
|
} |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
public function preUpdate(LifecycleEventArgs $args) |
|
52
|
|
|
{ |
|
53
|
|
|
$object = $args->getObject(); |
|
54
|
|
|
if ($object instanceof UserInterface) { |
|
55
|
|
|
/** @var EntityManagerInterface $em */ |
|
56
|
|
|
$em = $args->getObjectManager(); |
|
57
|
|
|
|
|
58
|
|
|
$this->updateUserFields($object); |
|
59
|
|
|
$this->recomputeChangeSet($em, $object); |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
private function updateUserFields(UserInterface $user) |
|
64
|
|
|
{ |
|
65
|
|
|
$plain = $user->getPlainPassword(); |
|
66
|
|
|
if (null !== $plain) { |
|
67
|
|
|
$hasher = $this->hasher; |
|
68
|
|
|
$password = $hasher->hashPassword($user, $plain); |
|
69
|
|
|
$user->setPassword($password); |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
private function recomputeChangeSet(EntityManagerInterface $em, UserInterface $user) |
|
74
|
|
|
{ |
|
75
|
|
|
$meta = $em->getClassMetadata(\get_class($user)); |
|
76
|
|
|
$em->getUnitOfWork()->recomputeSingleEntityChangeSet($meta, $user); |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|