AttributeCreatorListener   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 4
Bugs 1 Features 0
Metric Value
wmc 9
c 4
b 1
f 0
lcom 1
cbo 7
dl 0
loc 71
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B postLoad() 0 47 6
A getEntities() 0 8 2
1
<?php
2
3
namespace Padam87\AttributeBundle\EventListener;
4
5
use Doctrine\Common\Annotations\AnnotationReader;
6
use Doctrine\DBAL\DBALException;
7
use Doctrine\ORM\Event\LifecycleEventArgs;
8
use Doctrine\ORM\UnitOfWork;
9
use Padam87\AttributeBundle\Entity\Attribute;
10
use Padam87\AttributeBundle\Entity\Schema;
11
12
class AttributeCreatorListener
13
{
14
    private $entities = null;
15
16
    private $cacheDir;
17
18
    public function __construct($cacheDir)
19
    {
20
        $this->cacheDir = $cacheDir;
21
    }
22
23
    public function postLoad(LifecycleEventArgs $eventArgs)
24
    {
25
        $em = $eventArgs->getEntityManager();
26
        $uow = $em->getUnitOfWork();
27
        $entity = $eventArgs->getEntity();
28
        $classname = get_class($entity);
29
30
        if (!array_key_exists($classname, $this->getEntities())) {
31
            return null;
32
        }
33
34
        /** @var Schema $schema */
35
        $schema = $em->getRepository('Padam87AttributeBundle:Schema')->findOneBy([
36
            'className' => $classname,
37
        ]);
38
39
        if ($schema === null) {
40
            throw new \UnexpectedValueException('Schema not found for ' . $classname);
41
        }
42
43
        $qb = $em->getRepository($classname)->createQueryBuilder('main');
44
45
        $qb
46
            ->distinct()
47
            ->select('d.id')
48
            ->join('main.attributes', 'a')
49
            ->join('a.definition', 'd', null, null, 'd.id')
50
            ->where('main = :main')
51
            ->setParameter('main', $entity)
52
        ;
53
54
        $definitions = $qb->getQuery()->getArrayResult();
55
56
        foreach ($schema->getDefinitions() as $definition) {
57
            if (!array_key_exists($definition->getId(), $definitions)) {
58
                $attribute = new Attribute();
59
                $attribute->setDefinition($definition);
60
61
                $entity->addAttribute($attribute);
62
            }
63
        }
64
65
        if ($uow->getEntityState($entity) == UnitOfWork::STATE_MANAGED) {
66
            $em->persist($entity);
67
            $em->flush($entity);
68
        }
69
    }
70
71
    /**
72
     * @return array
73
     */
74
    protected function getEntities()
75
    {
76
        if ($this->entities === null) {
77
            $this->entities = include $this->cacheDir . '/padam87/attribute_bundle/Entity.cache.php';
78
        }
79
80
        return $this->entities;
81
    }
82
}
83