Passed
Push — main ( b2d943...872826 )
by Daniel
05:35
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 1
Bugs 0 Features 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 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 ApiPlatform\Metadata\IriConverterInterface;
17
use Doctrine\ORM\Mapping\ClassMetadataInfo;
18
use Doctrine\Persistence\ManagerRegistry;
19
use Silverback\ApiComponentsBundle\DataProvider\PageDataProvider;
20
use Silverback\ApiComponentsBundle\Entity\Core\AbstractComponent;
21
use Silverback\ApiComponentsBundle\Entity\Core\ComponentPosition;
22
use Silverback\ApiComponentsBundle\Exception\InvalidArgumentException;
23
use Silverback\ApiComponentsBundle\Helper\ComponentPosition\ComponentPositionSortValueHelper;
24
use Silverback\ApiComponentsBundle\Helper\Publishable\PublishableStatusChecker;
25
use Silverback\ApiComponentsBundle\Serializer\ResourceMetadata\ResourceMetadataProvider;
26
use Symfony\Component\HttpFoundation\RequestStack;
27
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
28
use Symfony\Component\PropertyAccess\Exception\NoSuchIndexException;
29
use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
30
use Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException;
31
use Symfony\Component\PropertyAccess\PropertyAccess;
32
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
33
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
34
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
35
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
36
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
37
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
38
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
39
40
/**
41
 * When creating a new component position the sort value should be set if not already explicitly set in the request.
42
 *
43
 * @author Daniel West <[email protected]>
44
 */
45
class ComponentPositionNormalizer implements DenormalizerInterface, DenormalizerAwareInterface, NormalizerInterface, NormalizerAwareInterface
46
{
47
    use DenormalizerAwareTrait;
48
    use NormalizerAwareTrait;
49
50
    private const ALREADY_CALLED = 'COMPONENT_POSITION_NORMALIZER_ALREADY_CALLED';
51
52
    public function __construct(
53
        private readonly PageDataProvider $pageDataProvider,
54
        private readonly ComponentPositionSortValueHelper $componentPositionSortValueHelper,
55
        private readonly RequestStack $requestStack,
56
        private readonly PublishableStatusChecker $publishableStatusChecker,
57
        private readonly ManagerRegistry $registry,
58
        private readonly IriConverterInterface $iriConverter,
59
        private readonly ResourceMetadataProvider $resourceMetadataProvider
60
    ) {
61
    }
62
63
    public function supportsDenormalization($data, $type, $format = null, array $context = []): bool
64
    {
65
        return !isset($context[self::ALREADY_CALLED]) && ComponentPosition::class === $type;
66
    }
67
68
    public function denormalize($data, $type, $format = null, array $context = []): ComponentPosition
69
    {
70
        $context[self::ALREADY_CALLED] = true;
71
72
        $originalObject = $context[AbstractNormalizer::OBJECT_TO_POPULATE] ?? null;
73
        $originalSortValue = $originalObject ? $originalObject->sortValue : null;
74
75
        /** @var ComponentPosition $object */
76
        $object = $this->denormalizer->denormalize($data, $type, $format, $context);
77
78
        $this->componentPositionSortValueHelper->calculateSortValue($object, $originalSortValue);
79
80
        return $object;
81
    }
82
83
    public function supportsNormalization($data, $format = null, array $context = []): bool
84
    {
85
        return $data instanceof ComponentPosition && !isset($context[self::ALREADY_CALLED]);
86
    }
87
88
    public function normalize($object, $format = null, array $context = []): float|array|\ArrayObject|bool|int|string|null
89
    {
90
        /* @var ComponentPosition $object */
91
        /* @var mixed|null        $format */
92
93
        $context[self::ALREADY_CALLED] = true;
94
95
        $staticComponent = $object->component;
96
        $resourceMetadata = $this->resourceMetadataProvider->findResourceMetadata($object);
97
98
        $object = $this->normalizeForPageData($object);
99
        if ($object->pageDataProperty) {
100
            $resourceMetadata->setIsDynamicPosition(true);
101
            try {
102
                $resourceMetadata->setPageDataPath($this->pageDataProvider->getOriginalRequestPath());
103
            } catch (UnprocessableEntityHttpException $e) {
104
                // the path header may not exist
105
            }
106
        } else {
107
            $resourceMetadata->setIsDynamicPosition(false);
108
        }
109
110
        if ($object->component) {
111
            $object->component = $this->getPublishableComponent($object->component);
112
        }
113
        if ($staticComponent) {
114
            $resourceMetadata->setStaticComponent($this->iriConverter->getIriFromResource($this->getPublishableComponent($staticComponent)));
0 ignored issues
show
Bug introduced by
It seems like $this->iriConverter->get...nent($staticComponent)) can also be of type null; however, parameter $staticComponentIri of Silverback\ApiComponents...a::setStaticComponent() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

114
            $resourceMetadata->setStaticComponent(/** @scrutinizer ignore-type */ $this->iriConverter->getIriFromResource($this->getPublishableComponent($staticComponent)));
Loading history...
115
        }
116
117
        return $this->normalizer->normalize($object, $format, $context);
118
    }
119
120
    private function getPublishableComponent($component)
121
    {
122
        if (
123
            $component
124
            && $this->publishableStatusChecker->getAttributeReader()->isConfigured($component)
125
            && $this->publishableStatusChecker->isGranted($component)
126
        ) {
127
            return $this->normalizePublishableComponent($component);
128
        }
129
130
        return $component;
131
    }
132
133
    private function normalizePublishableComponent(AbstractComponent $component)
134
    {
135
        $configuration = $this->publishableStatusChecker->getAttributeReader()->getConfiguration($type = $component::class);
136
        $em = $this->registry->getManagerForClass($component::class);
137
        if (!$em) {
138
            throw new InvalidArgumentException(sprintf('Could not find entity manager for class %s', $type));
0 ignored issues
show
Bug introduced by
It seems like $type can also be of type object; however, parameter $values of sprintf() does only seem to accept double|integer|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

138
            throw new InvalidArgumentException(sprintf('Could not find entity manager for class %s', /** @scrutinizer ignore-type */ $type));
Loading history...
139
        }
140
        /** @var ClassMetadataInfo $classMetadata */
141
        $classMetadata = $em->getClassMetadata($type);
0 ignored issues
show
Bug introduced by
It seems like $type can also be of type object; however, parameter $className of Doctrine\Persistence\Obj...ger::getClassMetadata() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

141
        $classMetadata = $em->getClassMetadata(/** @scrutinizer ignore-type */ $type);
Loading history...
142
        $draft = $classMetadata->getFieldValue($component, $configuration->reverseAssociationName);
143
144
        return $draft ?? $component;
145
    }
146
147
    private function normalizeForPageData(ComponentPosition $object): ComponentPosition
148
    {
149
        if (!$object->pageDataProperty || !$this->requestStack->getCurrentRequest()) {
150
            return $object;
151
        }
152
        try {
153
            $pageData = $this->pageDataProvider->getPageData();
154
        } catch (UnprocessableEntityHttpException $e) {
155
            // when serializing for mercure, we do not need the path header
156
            return $object;
157
        }
158
159
        if (!$pageData) {
160
            return $object;
161
        }
162
163
        $propertyAccessor = PropertyAccess::createPropertyAccessor();
164
        try {
165
            $component = $propertyAccessor->getValue($pageData, $object->pageDataProperty);
166
        } catch (UnexpectedTypeException|NoSuchIndexException|NoSuchPropertyException $e) {
167
            return $object;
168
        }
169
170
        // optional to have the page data component found
171
        if (!$component) {
172
            return $object;
173
        }
174
175
        // it must be a component if it is found though
176
        if (!$component instanceof AbstractComponent) {
177
            throw new InvalidArgumentException(sprintf('The page data property %s is not a component', $object->pageDataProperty));
178
        }
179
180
        // populate the position
181
        $object->setComponent($component);
182
183
        return $object;
184
    }
185
186
    public function getSupportedTypes(?string $format): array
0 ignored issues
show
Unused Code introduced by
The parameter $format is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

186
    public function getSupportedTypes(/** @scrutinizer ignore-unused */ ?string $format): array

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
187
    {
188
        return [ComponentPosition::class => false];
189
    }
190
}
191