Passed
Push — master ( bf17ee...5c8624 )
by Daniel
10:36
created

CwaResourceLoader   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 30
ccs 0
cts 15
cp 0
rs 10
wmc 7

1 Method

Rating   Name   Duplication   Size   Complexity  
B loadClassMetadata() 0 23 7
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 Silverback\ApiComponentsBundle\Entity\Core\AbstractPageData;
18
use Symfony\Component\Serializer\Mapping\ClassMetadataInterface;
19
use Symfony\Component\Serializer\Mapping\Loader\LoaderInterface;
20
21
/**
22
 * 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.
23
 *
24
 * @author Daniel West <[email protected]>
25
 */
26
final class CwaResourceLoader implements LoaderInterface
27
{
28
    public const GROUP_NAME = 'cwa_resource';
29
30
    /**
31
     * {@inheritdoc}
32
     */
33
    public function loadClassMetadata(ClassMetadataInterface $classMetadata): bool
34
    {
35
        $reflectionClass = $classMetadata->getReflectionClass();
36
        if (AbstractComponent::class !== $reflectionClass->getName() && !$reflectionClass->isSubclassOf(AbstractComponent::class) && !$reflectionClass->isSubclassOf(AbstractPageData::class)) {
37
            return true;
38
        }
39
40
        $allAttributesMetadata = $classMetadata->getAttributesMetadata();
41
        $shortClassName = $reflectionClass->getShortName();
42
        $readGroup = sprintf('%s:%s:read', $shortClassName, self::GROUP_NAME);
43
        $writeGroup = sprintf('%s:%s:write', $shortClassName, self::GROUP_NAME);
44
45
        foreach ($allAttributesMetadata as $attributeMetadatum) {
46
            if ('id' === $attributeMetadatum->getName()) {
47
                continue;
48
            }
49
            if (empty($attributeMetadatum->getGroups())) {
50
                $attributeMetadatum->addGroup($readGroup);
51
                $attributeMetadatum->addGroup($writeGroup);
52
            }
53
        }
54
55
        return true;
56
    }
57
}
58