Passed
Push — feature/uploadable ( 7c6d25...a7ed20 )
by Daniel
11:07
created

PublishableLoader::loadClassMetadata()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
eloc 17
c 0
b 0
f 0
dl 0
loc 29
ccs 0
cts 16
cp 0
rs 9.0777
cc 6
nc 5
nop 1
crap 42
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 Doctrine\Common\Annotations\AnnotationReader;
17
use Silverback\ApiComponentsBundle\Annotation\Publishable;
18
use Symfony\Component\Serializer\Mapping\ClassMetadataInterface;
19
use Symfony\Component\Serializer\Mapping\Loader\LoaderInterface;
20
21
/**
22
 * Adds {CLASS}:publishable serialization group on {CLASS}.publishedAt and {CLASS}.publishedResource for Publishable entities.
23
 *
24
 * @author Vincent Chalamon <[email protected]>
25
 */
26
final class PublishableLoader implements LoaderInterface
27
{
28
    public const GROUP_NAME = 'published';
29
30
    private AnnotationReader $reader;
31
32
    public function __construct(AnnotationReader $reader)
33
    {
34
        $this->reader = $reader;
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function loadClassMetadata(ClassMetadataInterface $classMetadata): bool
41
    {
42
        $reflectionClass = $classMetadata->getReflectionClass();
43
        /** @var Publishable $configuration */
44
        if (!$configuration = $this->reader->getClassAnnotation($reflectionClass, Publishable::class)) {
45
            return true;
46
        }
47
48
        $allAttributesMetadata = $classMetadata->getAttributesMetadata();
49
        $shortClassName = $reflectionClass->getShortName();
50
        $readGroup = sprintf('%s:%s:read', $shortClassName, self::GROUP_NAME);
51
        $writeGroup = sprintf('%s:%s:write', $shortClassName, self::GROUP_NAME);
52
53
        if (
54
            ($attributeMetadata = ($allAttributesMetadata[$configuration->fieldName] ?? null)) &&
55
            !empty($attributeMetadata->getGroups())
56
        ) {
57
            $attributeMetadata->addGroup($readGroup);
58
            $attributeMetadata->addGroup($writeGroup);
59
        }
60
61
        if (
62
            ($attributeMetadata = ($allAttributesMetadata[$configuration->associationName] ?? null)) &&
63
            !empty($attributeMetadata->getGroups())
64
        ) {
65
            $attributeMetadata->addGroup($readGroup);
66
        }
67
68
        return true;
69
    }
70
}
71