Passed
Pull Request — master (#73)
by Daniel
06:36
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\Helper\Collection\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
class AbstractComponentNormalizer implements ContextAwareDenormalizerInterface, CacheableSupportsMethodInterface, DenormalizerAwareInterface
24
{
25
    use DenormalizerAwareTrait;
26
27
    private const ALREADY_CALLED = 'ABSTRACT_COMPONENT_NORMALIZER_ALREADY_CALLED';
28
29
    private ApiResourceRouteFinder $routeFinder;
30
31 7
    public function __construct(ApiResourceRouteFinder $routeFinder)
32
    {
33 7
        $this->routeFinder = $routeFinder;
34 7
    }
35
36
    public function hasCacheableSupportsMethod(): bool
37
    {
38
        return false;
39
    }
40
41
    public function supportsDenormalization($data, $type, $format = null, array $context = []): bool
42
    {
43
        return !isset($context[self::ALREADY_CALLED]) && AbstractComponent::class === $type;
44
    }
45
46
    public function denormalize($data, $type, $format = null, array $context = [])
47
    {
48
        $context[self::ALREADY_CALLED] = true;
49
50
        if (\is_string($data)) {
51
            $iri = $data;
52
        } else {
53
            $iri = $data['@id'] ?? null;
54
        }
55
        if ($iri) {
56
            $routeParameters = $this->routeFinder->findByIri($iri);
57
            $type = $routeParameters['_api_resource_class'];
58
        }
59
60
        return $this->denormalizer->denormalize($data, $type, $format, $context);
61
    }
62
}
63