Passed
Push — v2 ( 9b5f7a...c6edc5 )
by Daniel
05:07
created

ApiNormalizer::hasCacheableSupportsMethod()   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
rs 10
ccs 0
cts 2
cp 0
cc 1
nc 1
nop 0
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;
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
use function is_object;
25
26
/**
27
 * @author Daniel West <[email protected]>
28
 */
29
class ApiNormalizer implements ContextAwareNormalizerInterface, CacheableSupportsMethodInterface, NormalizerAwareInterface
30
{
31
    use NormalizerAwareTrait;
32
    use ClassInfoTrait;
33
34
    private const ALREADY_CALLED = 'API_NORMALIZER_ALREADY_CALLED';
35
36
    private EntityManagerInterface $entityManager;
37
    private ResourceClassResolverInterface $resourceClassResolver;
38
39
    public function __construct(
40
        EntityManagerInterface $entityManager,
41
        ResourceClassResolverInterface $resourceClassResolver
42
    )
43
    {
44
        $this->entityManager = $entityManager;
45
        $this->resourceClassResolver = $resourceClassResolver;
46
    }
47
48
    public function normalize($object, $format = null, array $context = [])
49
    {
50
        $context[self::ALREADY_CALLED] = true;
51
52
        $data = $this->normalizer->normalize($object, $format, $context);
53
        if (is_array($data)) {
54
            $data['__PERSISTED__'] = $this->entityManager->contains($object);
55
        }
56
57
        return $data;
58
    }
59
60
    public function supportsNormalization($data, $format = null, $context = []): bool
61
    {
62
        if (isset($context[self::ALREADY_CALLED])) {
63
            return false;
64
        }
65
66
        if (!is_object($data) || $data instanceof Traversable) {
67
            return false;
68
        }
69
        return $this->resourceClassResolver->isResourceClass($this->getObjectClass($data));
70
    }
71
72
    public function hasCacheableSupportsMethod(): bool
73
    {
74
        return false;
75
    }
76
}
77