Passed
Pull Request — master (#73)
by Daniel
06:37
created

supportsDenormalization()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 1
nc 2
nop 4
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 6
rs 10
c 1
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 AbstractComponentNormalizer 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
        return !isset($context[self::ALREADY_CALLED]) && AbstractComponent::class === $type;
47
    }
48
49
    public function denormalize($data, $type, $format = null, array $context = [])
50
    {
51
        $context[self::ALREADY_CALLED] = true;
52
53
        if (\is_string($data)) {
54
            $iri = $data;
55
        } else {
56
            $iri = $data['@id'] ?? null;
57
        }
58
        if ($iri) {
59
            $routeParameters = $this->routeFinder->findByIri($iri);
60
            $type = $routeParameters['_api_resource_class'];
61
        }
62
63
        return $this->denormalizer->denormalize($data, $type, $format, $context);
64
    }
65
}
66