Passed
Push — master ( e9c651...e1baf6 )
by Christian
02:19
created

UniqueActiveListener::loadClassMetadata()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 18
rs 9.6111
c 0
b 0
f 0
cc 5
nc 4
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * (c) Christian Gripp <[email protected]>
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 Core23\Doctrine\EventListener\ORM;
13
14
use Core23\Doctrine\Model\UniqueActiveInterface;
15
use Doctrine\Common\EventSubscriber;
16
use Doctrine\ORM\Event\LifecycleEventArgs;
17
use Doctrine\ORM\Event\LoadClassMetadataEventArgs;
18
use Doctrine\ORM\Events;
19
use Doctrine\ORM\Mapping\ClassMetadata;
20
use Doctrine\ORM\Mapping\MappingException;
21
use Symfony\Component\PropertyAccess\PropertyAccess;
22
23
final class UniqueActiveListener implements EventSubscriber
24
{
25
    /**
26
     * {@inheritdoc}
27
     */
28
    public function getSubscribedEvents()
29
    {
30
        return [
31
            Events::prePersist,
32
            Events::preUpdate,
33
            Events::loadClassMetadata,
34
        ];
35
    }
36
37
    /**
38
     * @param LifecycleEventArgs $args
39
     */
40
    public function prePersist(LifecycleEventArgs $args): void
41
    {
42
        $this->uniqueActive($args);
43
    }
44
45
    /**
46
     * @param LifecycleEventArgs $args
47
     */
48
    public function preUpdate(LifecycleEventArgs $args): void
49
    {
50
        $this->uniqueActive($args);
51
    }
52
53
    /**
54
     * @param LoadClassMetadataEventArgs $eventArgs
55
     *
56
     * @throws MappingException
57
     */
58
    public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs): void
59
    {
60
        $meta = $eventArgs->getClassMetadata();
61
62
        if (!$meta instanceof ClassMetadata) {
0 ignored issues
show
introduced by core23
$meta is always a sub-type of Doctrine\ORM\Mapping\ClassMetadata.
Loading history...
63
            throw new \LogicException(sprintf('Class metadata was no ORM but %s', \get_class($meta)));
64
        }
65
66
        $reflClass = $meta->getReflectionClass();
67
68
        if (null === $reflClass || !$reflClass->implementsInterface(UniqueActiveInterface::class)) {
69
            return;
70
        }
71
72
        if (!$meta->hasField('active')) {
73
            $meta->mapField([
74
                'type'      => 'integer',
75
                'fieldName' => 'active',
76
            ]);
77
        }
78
    }
79
80
    /**
81
     * @param LifecycleEventArgs $args
82
     */
83
    private function uniqueActive(LifecycleEventArgs $args): void
84
    {
85
        $entity = $args->getEntity();
86
87
        if ($entity instanceof UniqueActiveInterface && $entity->isActive()) {
88
            $em   = $args->getEntityManager();
89
            $uow  = $em->getUnitOfWork();
90
            $meta = $em->getClassMetadata(\get_class($entity));
91
92
            $qb = $em->createQueryBuilder()
93
                ->update($meta->getName(), 'e')
94
                ->set('e.active', 'false')
95
                ->andWhere('e.active = true');
96
97
            $propertyAccessor = PropertyAccess::createPropertyAccessor();
98
99
            foreach ($meta->getIdentifier() as $key) {
100
                $qb->andWhere(sprintf('e.%s != :%s', $key, $key))
101
                    ->setParameter($key, $propertyAccessor->getValue($entity, $key));
102
            }
103
104
            foreach ($entity->getUniqueActiveFields() as $field) {
105
                $value = $propertyAccessor->getValue($entity, $field);
106
107
                if (\is_object($value) && null === $uow->getSingleIdentifierValue($value)) {
108
                    continue;
109
                }
110
111
                $qb->andWhere('e.'.$field.' = :'.$field)->setParameter($field, $value);
112
            }
113
114
            $qb->getQuery()->execute();
115
        }
116
    }
117
}
118