Passed
Pull Request — master (#52)
by Daniel
06:09
created

UploadableListener::loadClassMetadata()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5.009

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 22
ccs 13
cts 14
cp 0.9286
rs 9.4888
cc 5
nc 5
nop 1
crap 5.009
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Component Bundle Project
5
 *
6
 * (c) Daniel West <[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
declare(strict_types=1);
13
14
namespace Silverback\ApiComponentBundle\EventListener\Doctrine;
15
16
use Doctrine\ORM\EntityManagerInterface;
17
use Doctrine\ORM\Mapping\ClassMetadataInfo;
18
use Doctrine\Persistence\Event\LoadClassMetadataEventArgs;
19
use Silverback\ApiComponentBundle\AnnotationReader\UploadableAnnotationReader;
20
21
/**
22
 * @author Vincent Chalamon <[email protected]>
23
 */
24
final class UploadableListener
25
{
26
    private UploadableAnnotationReader $uploadableAnnotationReader;
27
28 9
    public function __construct(UploadableAnnotationReader $uploadableAnnotationReader)
29
    {
30 9
        $this->uploadableAnnotationReader = $uploadableAnnotationReader;
31 9
    }
32
33 9
    public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs): void
34
    {
35
        /** @var ClassMetadataInfo $metadata */
36 9
        $metadata = $eventArgs->getClassMetadata();
37 9
        $className = $metadata->getName();
38 9
        if (!$this->uploadableAnnotationReader->isConfigured($className)) {
39 9
            return;
40
        }
41
42 9
        $em = $eventArgs->getObjectManager();
43 9
        if (!$em instanceof EntityManagerInterface) {
44
            return;
45
        }
46
47 9
        $propertyConfigurations = $this->uploadableAnnotationReader->getConfiguredProperties($className, true, true);
48
49 9
        foreach ($propertyConfigurations as $propertyConfiguration) {
50 9
            if (!$metadata->hasField($propertyConfiguration->property)) {
51 9
                $metadata->mapField([
52 9
                    'fieldName' => $propertyConfiguration->property,
53 9
                    'type' => 'string',
54
                    'nullable' => true,
55
                ]);
56
            }
57
        }
58 9
    }
59
}
60