Passed
Push — feature/uploadable ( 7c6d25...a7ed20 )
by Daniel
11:07
created

PersistedNormalizer::normalize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 3
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
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\Normalizer;
15
16
use ApiPlatform\Core\Api\ResourceClassResolverInterface;
17
use ApiPlatform\Core\Util\ClassInfoTrait;
18
use Doctrine\ORM\EntityManagerInterface;
19
use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
20
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
21
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
22
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
23
use Traversable;
24
25
/**
26
 * @author Daniel West <[email protected]>
27
 */
28
class PersistedNormalizer implements ContextAwareNormalizerInterface, CacheableSupportsMethodInterface, NormalizerAwareInterface
29
{
30
    use NormalizerAwareTrait;
31
    use ClassInfoTrait;
32
33
    private const ALREADY_CALLED = 'PERSISTED_NORMALIZER_ALREADY_CALLED';
34
35
    private EntityManagerInterface $entityManager;
36
    private ResourceClassResolverInterface $resourceClassResolver;
37
38 6
    public function __construct(
39
        EntityManagerInterface $entityManager,
40
        ResourceClassResolverInterface $resourceClassResolver
41
    ) {
42 6
        $this->entityManager = $entityManager;
43 6
        $this->resourceClassResolver = $resourceClassResolver;
44 6
    }
45
46 2
    public function normalize($object, $format = null, array $context = [])
47
    {
48 2
        $context[self::ALREADY_CALLED] = true;
49 2
        $context[MetadataNormalizer::METADATA_CONTEXT]['persisted'] = $this->entityManager->contains($object);
50
51 2
        return $this->normalizer->normalize($object, $format, $context);
52
    }
53
54 3
    public function supportsNormalization($data, $format = null, $context = []): bool
55
    {
56 3
        if (isset($context[self::ALREADY_CALLED])) {
57 1
            return false;
58
        }
59
60 3
        if (!\is_object($data) || $data instanceof Traversable) {
61 1
            return false;
62
        }
63
64 2
        return $this->resourceClassResolver->isResourceClass($this->getObjectClass($data));
65
    }
66
67 1
    public function hasCacheableSupportsMethod(): bool
68
    {
69 1
        return false;
70
    }
71
}
72