Passed
Pull Request — feature/publishable (#31)
by Vincent
06:03
created

PublishableLoader::loadClassMetadata()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 6
c 1
b 0
f 1
dl 0
loc 14
ccs 0
cts 7
cp 0
rs 10
cc 3
nc 3
nop 1
crap 12
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\Reader;
17
use Silverback\ApiComponentBundle\Annotation\Publishable;
18
use Symfony\Component\Serializer\Exception\MappingException;
19
use Symfony\Component\Serializer\Mapping\ClassMetadataInterface;
20
use Symfony\Component\Serializer\Mapping\Loader\LoaderInterface;
21
22
/**
23
 * Adds {CLASS}:publishable serialization group on {CLASS}.publishedAt for Publishable entities.
24
 *
25
 * @author Vincent Chalamon <[email protected]>
26
 */
27
final class PublishableLoader implements LoaderInterface
28
{
29
    private Reader $reader;
30
31
    public function __construct(Reader $reader)
32
    {
33
        $this->reader = $reader;
34
    }
35
36
    /**
37
     * {@inheritdoc}
38
     */
39
    public function loadClassMetadata(ClassMetadataInterface $classMetadata)
40
    {
41
        /** @var Publishable $annotation */
42
        if (!$annotation = $this->reader->getClassAnnotation($classMetadata->getReflectionClass(), Publishable::class)) {
43
            return true;
44
        }
45
46
        if (!$attributeMetadata = ($classMetadata->getAttributesMetadata()[$annotation->fieldName] ?? null)) {
47
            throw new MappingException(sprintf('Groups on "%s::%s" cannot be added because the field does not exist.', $classMetadata->getName(), $annotation->fieldName));
48
        }
49
50
        $attributeMetadata->addGroup(sprintf('%s:publishable', $classMetadata->getName()));
51
52
        return true;
53
    }
54
}
55