Passed
Push — feature/publishable ( 0a4351...5afc24 )
by Daniel
19:43 queued 12:43
created

PublishableLoader::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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