|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of AppName. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Monofony |
|
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
|
|
|
namespace App\EventListener; |
|
13
|
|
|
|
|
14
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
|
15
|
|
|
use Doctrine\ORM\Event\OnFlushEventArgs; |
|
16
|
|
|
use Doctrine\ORM\Mapping\ClassMetadata; |
|
17
|
|
|
use Doctrine\ORM\UnitOfWork; |
|
18
|
|
|
use App\Entity\Customer\CustomerInterface; |
|
19
|
|
|
use Sylius\Component\User\Model\UserInterface; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* Keeps user's username synchronized with email. |
|
23
|
|
|
*/ |
|
24
|
|
|
final class DefaultUsernameORMListener |
|
25
|
|
|
{ |
|
26
|
|
|
/** |
|
27
|
|
|
* @param OnFlushEventArgs $onFlushEventArgs |
|
28
|
|
|
*/ |
|
29
|
|
|
public function onFlush(OnFlushEventArgs $onFlushEventArgs): void |
|
30
|
|
|
{ |
|
31
|
|
|
$entityManager = $onFlushEventArgs->getEntityManager(); |
|
32
|
|
|
$unitOfWork = $entityManager->getUnitOfWork(); |
|
33
|
|
|
|
|
34
|
|
|
$this->processEntities($unitOfWork->getScheduledEntityInsertions(), $entityManager, $unitOfWork); |
|
35
|
|
|
$this->processEntities($unitOfWork->getScheduledEntityUpdates(), $entityManager, $unitOfWork); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* @param array $entities |
|
40
|
|
|
* @param EntityManagerInterface $entityManager |
|
41
|
|
|
*/ |
|
42
|
|
|
private function processEntities($entities, EntityManagerInterface $entityManager, UnitOfWork $unitOfWork): void |
|
43
|
|
|
{ |
|
44
|
|
|
foreach ($entities as $customer) { |
|
45
|
|
|
if (!$customer instanceof CustomerInterface) { |
|
46
|
|
|
continue; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** @var UserInterface $user */ |
|
50
|
|
|
$user = $customer->getUser(); |
|
51
|
|
|
|
|
52
|
|
|
if (null === $user) { |
|
53
|
|
|
continue; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
if ($customer->getEmail() === $user->getUsername() && $customer->getEmailCanonical() === $user->getUsernameCanonical()) { |
|
57
|
|
|
continue; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
$user->setUsername($customer->getEmail()); |
|
61
|
|
|
$user->setUsernameCanonical($customer->getEmailCanonical()); |
|
62
|
|
|
|
|
63
|
|
|
/** @var ClassMetadata $userMetadata */ |
|
64
|
|
|
$userMetadata = $entityManager->getClassMetadata(get_class($user)); |
|
65
|
|
|
$unitOfWork->recomputeSingleEntityChangeSet($userMetadata, $user); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|