Passed
Pull Request — master (#73)
by Daniel
05:33
created

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 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
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 Silverback\ApiComponentsBundle\Entity\Core\AbstractComponent;
17
use Silverback\ApiComponentsBundle\Utility\ApiResourceRouteFinder;
18
use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
19
use Symfony\Component\Serializer\Normalizer\ContextAwareDenormalizerInterface;
20
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
21
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
22
23
/**
24
 * @author Daniel West <[email protected]>
25
 */
26
class AbstractResourceNormalizer implements ContextAwareDenormalizerInterface, CacheableSupportsMethodInterface, DenormalizerAwareInterface
27
{
28
    use DenormalizerAwareTrait;
29
30
    private const ALREADY_CALLED = 'ABSTRACT_COMPONENT_NORMALIZER_ALREADY_CALLED';
31
32
    private ApiResourceRouteFinder $routeFinder;
33
34 7
    public function __construct(ApiResourceRouteFinder $routeFinder)
35
    {
36 7
        $this->routeFinder = $routeFinder;
37 7
    }
38
39
    public function hasCacheableSupportsMethod(): bool
40
    {
41
        return false;
42
    }
43
44
    public function supportsDenormalization($data, $type, $format = null, array $context = []): bool
45
    {
46
        try {
47
            return !isset($context[self::ALREADY_CALLED]) && (new \ReflectionClass($type))->isAbstract();
48
        } catch (\ReflectionException $exception) {
49
            return false;
50
        }
51
    }
52
53
    public function denormalize($data, $type, $format = null, array $context = [])
54
    {
55
        $context[self::ALREADY_CALLED] = true;
56
57
        if (\is_string($data)) {
58
            $iri = $data;
59
        } else {
60
            $iri = $data['@id'] ?? null;
61
        }
62
        if ($iri) {
63
            $routeParameters = $this->routeFinder->findByIri($iri);
64
            $type = $routeParameters['_api_resource_class'];
65
        }
66
67
        return $this->denormalizer->denormalize($data, $type, $format, $context);
68
    }
69
}
70