Passed
Push — master ( def3b9...9746d2 )
by Daniel
06:04
created

TimestampedLoader   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Test Coverage

Coverage 15%

Importance

Changes 0
Metric Value
eloc 22
c 0
b 0
f 0
dl 0
loc 44
ccs 3
cts 20
cp 0.15
rs 10
wmc 7

2 Methods

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