TimestampedLoader   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 22
dl 0
loc 38
ccs 0
cts 19
cp 0
rs 10
c 0
b 0
f 0
wmc 6

1 Method

Rating   Name   Duplication   Size   Complexity  
B loadClassMetadata() 0 31 6
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Components 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\ApiComponentsBundle\Serializer\MappingLoader;
15
16
use Silverback\ApiComponentsBundle\Annotation\Timestamped;
17
use Symfony\Component\Serializer\Mapping\ClassMetadataInterface;
18
use Symfony\Component\Serializer\Mapping\Loader\LoaderInterface;
19
20
/**
21
 * Adds {CLASS}:timestamped serialization group on {CLASS}.createdAt and {CLASS}.updatedAt for Timestamped entities.
22
 *
23
 * @author Daniel West <[email protected]>
24
 */
25
final class TimestampedLoader implements LoaderInterface
26
{
27
    public const GROUP_NAME = 'timestamped';
28
29
    /**
30
     * {@inheritdoc}
31
     */
32
    public function loadClassMetadata(ClassMetadataInterface $classMetadata): bool
33
    {
34
        $reflectionClass = $classMetadata->getReflectionClass();
35
        $attributes = $reflectionClass->getAttributes(Timestamped::class);
36
        if (!\count($attributes)) {
37
            return true;
38
        }
39
        /** @var Timestamped $configuration */
40
        $configuration = $attributes[0]->newInstance();
41
42
        $allAttributesMetadata = $classMetadata->getAttributesMetadata();
43
        $shortClassName = $reflectionClass->getShortName();
44
        $readGroup = sprintf('%s:%s:read', $shortClassName, self::GROUP_NAME);
45
        $writeGroup = sprintf('%s:%s:write', $shortClassName, self::GROUP_NAME);
46
        if (
47
            ($attributeMetadata = ($allAttributesMetadata[$configuration->createdAtField] ?? null))
48
            && empty($attributeMetadata->getGroups())
49
        ) {
50
            $attributeMetadata->addGroup($readGroup);
51
            $attributeMetadata->addGroup($writeGroup);
52
        }
53
54
        if (
55
            ($attributeMetadata = ($allAttributesMetadata[$configuration->modifiedAtField] ?? null))
56
            && empty($attributeMetadata->getGroups())
57
        ) {
58
            $attributeMetadata->addGroup($readGroup);
59
            $attributeMetadata->addGroup($writeGroup);
60
        }
61
62
        return true;
63
    }
64
}
65