Test Failed
Pull Request — feature/publishable (#31)
by Vincent
06:22
created

PublishableLoader::loadClassMetadata()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 12
c 1
b 0
f 1
dl 0
loc 23
rs 9.2222
cc 6
nc 6
nop 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 Silverback\ApiComponentBundle\Entity\Utility\PublishableInterface;
17
use Silverback\ApiComponentBundle\Publishable\PublishableHelper;
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
 * Adds {CLASS}:publishable serialization group on {CLASS}.isPublished for Publishable entities with PublishableInterface.
25
 *
26
 * @author Vincent Chalamon <[email protected]>
27
 */
28
final class PublishableLoader implements LoaderInterface
29
{
30
    private PublishableHelper $publishableHelper;
31
32
    public function __construct(PublishableHelper $publishableHelper)
33
    {
34
        $this->publishableHelper = $publishableHelper;
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function loadClassMetadata(ClassMetadataInterface $classMetadata)
41
    {
42
        if (!$this->publishableHelper->isPublishable($classMetadata->getName())) {
43
            return true;
44
        }
45
46
        $configuration = $this->publishableHelper->getConfiguration($classMetadata->getName());
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