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

PublishableLoader   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 26
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 4
eloc 9
c 1
b 0
f 1
dl 0
loc 26
ccs 0
cts 10
cp 0
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A loadClassMetadata() 0 14 3
A __construct() 0 3 1
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