UniqueStateAbleListener   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 4
Bugs 2 Features 1
Metric Value
wmc 5
c 4
b 2
f 1
lcom 0
cbo 1
dl 0
loc 46
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A postUpdate() 0 4 1
A getSubscribedEvents() 0 7 1
A postPersist() 0 21 3
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