Passed
Pull Request — master (#52)
by Vincent
11:12 queued 04:00
created

UploadableListener::loadClassMetadata()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 24
ccs 0
cts 15
cp 0
rs 9.2222
cc 6
nc 6
nop 1
crap 42
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\Helper\UploadableHelper;
20
21
/**
22
 * @author Vincent Chalamon <[email protected]>
23
 */
24
final class UploadableListener
25
{
26
    private UploadableHelper $uploadableHelper;
27
28
    public function __construct(UploadableHelper $uploadableHelper)
29
    {
30
        $this->uploadableHelper = $uploadableHelper;
31
    }
32
33
    public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs): void
34
    {
35
        /** @var ClassMetadataInfo $metadata */
36
        $metadata = $eventArgs->getClassMetadata();
37
        if (!$this->uploadableHelper->isConfigured($metadata->getName())) {
38
            return;
39
        }
40
41
        $em = $eventArgs->getObjectManager();
42
        if (!$em instanceof EntityManagerInterface) {
43
            return;
44
        }
45
46
        foreach ($metadata->getReflectionProperties() as $property) {
47
            if (!$this->uploadableHelper->isFieldConfigured($property)) {
48
                continue;
49
            }
50
51
            $fieldConfiguration = $this->uploadableHelper->getFieldConfiguration($property);
52
            if (!$metadata->hasField($fieldConfiguration->property)) {
53
                $metadata->mapField([
54
                    'fieldName' => $fieldConfiguration->property,
55
                    'type' => 'string',
56
                    'nullable' => true,
57
                ]);
58
            }
59
        }
60
        // todo Add security if no UploadableField has been configured on related entity
61
    }
62
}
63