Completed
Push — master ( fe8029...f95222 )
by Michał
432:28 queued 418:44
created

DefaultUsernameORMListener::processEntities()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 24
rs 8.5125
cc 6
eloc 13
nc 5
nop 3
1
<?php
2
3
/*
4
 * This file is part of the Sylius package.
5
 *
6
 * (c) Paweł Jędrzejewski
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 Sylius\Bundle\CoreBundle\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 Sylius\Component\Core\Model\CustomerInterface;
19
20
/**
21
 * Keeps user's username synchronized with email.
22
 *
23
 * @author Michał Marcinkowski <[email protected]>
24
 */
25
final class DefaultUsernameORMListener
26
{
27
    /**
28
     * @param OnFlushEventArgs $onFlushEventArgs
29
     */
30
    public function onFlush(OnFlushEventArgs $onFlushEventArgs)
31
    {
32
        $entityManager = $onFlushEventArgs->getEntityManager();
33
        $unitOfWork = $entityManager->getUnitOfWork();
34
35
        $this->processEntities($unitOfWork->getScheduledEntityInsertions(), $entityManager, $unitOfWork);
36
        $this->processEntities($unitOfWork->getScheduledEntityUpdates(), $entityManager, $unitOfWork);
37
    }
38
39
    /**
40
     * @param array $entities
41
     * @param EntityManagerInterface $entityManager
42
     */
43
    private function processEntities($entities, EntityManagerInterface $entityManager, UnitOfWork $unitOfWork)
44
    {
45
        foreach ($entities as $customer) {
46
            if (!$customer instanceof CustomerInterface) {
47
                continue;
48
            }
49
50
            $user = $customer->getUser();
51
            if (null === $user) {
52
                continue;
53
            }
54
55
            if ($customer->getEmail() === $user->getUsername() && $customer->getEmailCanonical() === $user->getUsernameCanonical()) {
56
                continue;
57
            }
58
59
            $user->setUsername($customer->getEmail());
60
            $user->setUsernameCanonical($customer->getEmailCanonical());
61
62
            /** @var ClassMetadata $userMetadata */
63
            $userMetadata = $entityManager->getClassMetadata(get_class($user));
64
            $unitOfWork->recomputeSingleEntityChangeSet($userMetadata, $user);
65
        }
66
    }
67
}
68