Passed
Push — master ( aa9d11...e7036c )
by Damien
03:01
created

AnnotationLoader::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 4
rs 10
1
<?php
2
3
namespace DH\DoctrineAuditBundle\Annotation;
4
5
use Doctrine\Common\Annotations\AnnotationReader;
6
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
7
use Doctrine\ORM\EntityManagerInterface;
8
use Doctrine\ORM\Mapping\Entity;
9
10
class AnnotationLoader
11
{
12
    /**
13
     * @var AnnotationReader
14
     */
15
    private $reader;
16
17
    /**
18
     * @var EntityManagerInterface
19
     */
20
    private $entityManager;
21
22
    public function __construct(EntityManagerInterface $entityManager)
23
    {
24
        $this->entityManager = $entityManager;
25
        $this->reader = new AnnotationReader();
26
    }
27
28
    public function load(): array
29
    {
30
        $configuration = array();
31
32
        $metadatas = $this->entityManager->getMetadataFactory()->getAllMetadata();
33
        foreach ($metadatas as $metadata) {
34
            $config = $this->getEntityConfiguration($metadata);
35
            if (null !== $config) {
36
                $configuration[$metadata->getName()] = $config;
37
            }
38
        }
39
40
        return $configuration;
41
    }
42
43
    private function getEntityConfiguration(ClassMetadata $metadata): ?array
44
    {
45
        $reflection = $metadata->getReflectionClass();
46
47
        // Check that we have an Entity annotation
48
        $annotation = $this->reader->getClassAnnotation($reflection, Entity::class);
49
        if (null === $annotation) {
50
            return null;
51
        }
52
53
        // Check that we have an Auditable annotation
54
        $annotation = $this->reader->getClassAnnotation($reflection, Auditable::class);
55
        if (null === $annotation) {
56
            return null;
57
        }
58
59
        $config =  [
60
            'ignored_columns' => [],
61
            'enabled' => $annotation->enabled,
62
        ];
63
64
        // Are there any Ignore annotations?
65
        foreach ($reflection->getProperties() as $property) {
66
            if ($this->reader->getPropertyAnnotation($property, Ignore::class)) {
67
                // TODO: $property->getName() might not be the column name
68
                $config['ignored_columns'][] = $property->getName();
69
            }
70
        }
71
72
        return $config;
73
    }
74
}
75