Passed
Push — master ( 3ec415...9f2f47 )
by Daniel
16:25
created

ComponentLoader::loadClassMetadata()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 6
eloc 14
nc 5
nop 1
dl 0
loc 23
ccs 0
cts 15
cp 0
crap 42
rs 9.2222
c 1
b 1
f 0
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Components 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\ApiComponentsBundle\Serializer\MappingLoader;
15
16
use Silverback\ApiComponentsBundle\Entity\Core\AbstractComponent;
17
use Symfony\Component\Serializer\Mapping\ClassMetadataInterface;
18
use Symfony\Component\Serializer\Mapping\Loader\LoaderInterface;
19
20
/**
21
 * Adds {CLASS}:component serialization groups on component entities. This will allow cascaded persists by default and every property accessible by read/write unless a serialization group has been specifically defined on a property.
22
 *
23
 * @author Daniel West <[email protected]>
24
 */
25
final class ComponentLoader implements LoaderInterface
26
{
27
    public const GROUP_NAME = 'component';
28
29
    /**
30
     * {@inheritdoc}
31
     */
32
    public function loadClassMetadata(ClassMetadataInterface $classMetadata): bool
33
    {
34
        $reflectionClass = $classMetadata->getReflectionClass();
35
        if (AbstractComponent::class !== $reflectionClass->getName() && !$reflectionClass->isSubclassOf(AbstractComponent::class)) {
36
            return true;
37
        }
38
39
        $allAttributesMetadata = $classMetadata->getAttributesMetadata();
40
        $shortClassName = $reflectionClass->getShortName();
41
        $readGroup = sprintf('%s:%s:read', $shortClassName, self::GROUP_NAME);
42
        $writeGroup = sprintf('%s:%s:write', $shortClassName, self::GROUP_NAME);
43
44
        foreach ($allAttributesMetadata as $attributeMetadatum) {
45
            if ('id' === $attributeMetadatum->getName()) {
46
                continue;
47
            }
48
            if (empty($attributeMetadatum->getGroups())) {
49
                $attributeMetadatum->addGroup($readGroup);
50
                $attributeMetadatum->addGroup($writeGroup);
51
            }
52
        }
53
54
        return true;
55
    }
56
}
57