Passed
Pull Request — feature/publishable (#31)
by Vincent
19:39 queued 09:22
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 1
Bugs 0 Features 1
Metric Value
eloc 1
c 1
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 Silverback\ApiComponentBundle\Entity\Utility\PublishableInterface;
19
use Symfony\Component\Serializer\Exception\MappingException;
20
use Symfony\Component\Serializer\Mapping\ClassMetadataInterface;
21
use Symfony\Component\Serializer\Mapping\Loader\LoaderInterface;
22
23
/**
24
 * Adds {CLASS}:publishable serialization group on {CLASS}.publishedAt for Publishable entities.
25
 * Adds {CLASS}:publishable serialization group on {CLASS}.isPublished for Publishable entities with PublishableInterface.
26
 *
27
 * @author Vincent Chalamon <[email protected]>
28
 */
29
final class PublishableLoader implements LoaderInterface
30
{
31
    private AnnotationReader $reader;
32
33
    public function __construct(AnnotationReader $reader)
34
    {
35
        $this->reader = $reader;
36
    }
37
38
    /**
39
     * {@inheritdoc}
40
     */
41
    public function loadClassMetadata(ClassMetadataInterface $classMetadata)
42
    {
43
        if (!$configuration = $this->reader->getClassAnnotation($classMetadata->getReflectionClass(), Publishable::class)) {
44
            return true;
45
        }
46
47
        foreach ([$configuration->fieldName, $configuration->associationName] as $field) {
48
            if (!$attributeMetadata = ($classMetadata->getAttributesMetadata()[$field] ?? null)) {
49
                throw new MappingException(sprintf('Groups on "%s::%s" cannot be added because the field does not exist.', $classMetadata->getName(), $field));
50
            }
51
52
            $attributeMetadata->addGroup(sprintf('%s:publishable', $classMetadata->getName()));
53
        }
54
55
        if (
56
            is_a($classMetadata->getName(), PublishableInterface::class, true) &&
57
            ($attributeMetadata = ($classMetadata->getAttributesMetadata()['isPublished'] ?? null))
58
        ) {
59
            $attributeMetadata->addGroup(sprintf('%s:publishable', $classMetadata->getName()));
60
        }
61
62
        return true;
63
    }
64
}
65