Passed
Push — feature/publishable ( c26268...7bd202 )
by Daniel
18:12 queued 11:31
created

TimestampedLoader::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
cc 1
nc 1
nop 1
crap 2
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\MappingLoader;
15
16
use Doctrine\Common\Annotations\AnnotationReader;
17
use Silverback\ApiComponentBundle\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
    public function __construct(AnnotationReader $reader)
33
    {
34
        $this->reader = $reader;
35
    }
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
52
        if (
53
            ($attributeMetadata = ($allAttributesMetadata[$configuration->createdAtField] ?? null)) &&
54
            !empty($attributeMetadata->getGroups())
55
        ) {
56
            $attributeMetadata->addGroup($readGroup);
57
        }
58
59
        if (
60
            ($attributeMetadata = ($allAttributesMetadata[$configuration->modifiedAtField] ?? null)) &&
61
            !empty($attributeMetadata->getGroups())
62
        ) {
63
            $attributeMetadata->addGroup($readGroup);
64
        }
65
66
        return true;
67
    }
68
}
69