UniqueStateAbleListener::postPersist()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.3142
c 0
b 0
f 0
nc 2
cc 3
eloc 14
nop 1
1
<?php
2
3
namespace DoS\ResourceBundle\EventListener;
4
5
use Doctrine\Common\EventSubscriber;
6
use Doctrine\ORM\Event\LifecycleEventArgs;
7
use DoS\ResourceBundle\Model\UniqueStateAbleInterface;
8
9
class UniqueStateAbleListener implements EventSubscriber
10
{
11
    /**
12
     * {@inheritdoc}
13
     */
14
    public function postPersist(LifecycleEventArgs $event)
15
    {
16
        $object = $event->getObject();
17
18
        if ($object instanceof UniqueStateAbleInterface && $object->getUniqueState()) {
19
            // with this approach `entities` will not take there's events.
20
            $em = $event->getEntityManager();
21
            $id = $em->getClassMetadata(get_class($object))->identifier[0];
22
23
            $em->createQueryBuilder()
24
                ->update(get_class($object), 'o')
25
                ->set('o.' . $object->getUniqueStateField(), ':update')
26
                ->where('o.' . $object->getUniqueStateField() . ' = :where')
27
                ->andWhere('o.' . $id . ' <> :self')
28
                ->setParameter('update', false)
29
                ->setParameter('where', true)
30
                ->setParameter('self', $object)
31
                ->getQuery()->execute()
32
            ;
33
        }
34
    }
35
36
    /**
37
     * {@inheritdoc}
38
     */
39
    public function postUpdate(LifecycleEventArgs $event)
40
    {
41
        $this->postPersist($event);
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    public function getSubscribedEvents()
48
    {
49
        return array(
50
            'postPersist',
51
            'postUpdate',
52
        );
53
    }
54
}
55