Passed
Push — v2 ( c3152c...b7bda3 )
by Daniel
05:06
created

ApiNormalizer::hasCacheableSupportsMethod()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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