Passed
Push — master ( e05727...cddc8e )
by Daniel
09:15
created

supportsNormalization()   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
eloc 1
nc 2
nop 3
dl 0
loc 3
c 1
b 0
f 0
cc 2
ccs 0
cts 2
cp 0
crap 6
rs 10
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\Core\Api\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\Exception\UnexpectedValueException;
24
use Silverback\ApiComponentsBundle\Helper\ComponentPosition\ComponentPositionSortValueHelper;
25
use Silverback\ApiComponentsBundle\Helper\Publishable\PublishableStatusChecker;
26
use Symfony\Component\HttpFoundation\RequestStack;
27
use Symfony\Component\PropertyAccess\Exception\NoSuchIndexException;
28
use Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException;
29
use Symfony\Component\PropertyAccess\PropertyAccess;
30
use Symfony\Component\Security\Core\Security;
31
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
32
use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
33
use Symfony\Component\Serializer\Normalizer\ContextAwareDenormalizerInterface;
34
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
35
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
36
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
37
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
38
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
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 CacheableSupportsMethodInterface, ContextAwareDenormalizerInterface, DenormalizerAwareInterface, ContextAwareNormalizerInterface, NormalizerAwareInterface
46
{
47
    use DenormalizerAwareTrait;
48
    use NormalizerAwareTrait;
49
50
    private const ALREADY_CALLED = 'COMPONENT_POSITION_NORMALIZER_ALREADY_CALLED';
51
52
    private PageDataProvider $pageDataProvider;
53
    private ComponentPositionSortValueHelper $componentPositionSortValueHelper;
54
    private RequestStack $requestStack;
55
    private Security $security;
56
    private PublishableStatusChecker $publishableStatusChecker;
57
    private ManagerRegistry $registry;
58
    private IriConverterInterface $iriConverter;
59
60
    public function __construct(
61
        PageDataProvider $pageDataProvider,
62
        ComponentPositionSortValueHelper $componentPositionSortValueHelper,
63
        RequestStack $requestStack,
64
        Security $security,
65
        PublishableStatusChecker $publishableStatusChecker,
66
        ManagerRegistry $registry,
67
        IriConverterInterface $iriConverter
68
    ) {
69
        $this->pageDataProvider = $pageDataProvider;
70
        $this->componentPositionSortValueHelper = $componentPositionSortValueHelper;
71
        $this->requestStack = $requestStack;
72
        $this->security = $security;
73
        $this->publishableStatusChecker = $publishableStatusChecker;
74
        $this->registry = $registry;
75
        $this->iriConverter = $iriConverter;
76
    }
77
78
    public function hasCacheableSupportsMethod(): bool
79
    {
80
        return false;
81
    }
82
83
    public function supportsDenormalization($data, $type, $format = null, array $context = []): bool
84
    {
85
        return !isset($context[self::ALREADY_CALLED]) && ComponentPosition::class === $type;
86
    }
87
88
    public function denormalize($data, $type, $format = null, array $context = [])
89
    {
90
        $context[self::ALREADY_CALLED] = true;
91
92
        $originalObject = $context[AbstractNormalizer::OBJECT_TO_POPULATE] ?? null;
93
        $originalSortValue = $originalObject ? $originalObject->sortValue : null;
94
95
        /** @var ComponentPosition $object */
96
        $object = $this->denormalizer->denormalize($data, $type, $format, $context);
97
98
        $this->componentPositionSortValueHelper->calculateSortValue($object, $originalSortValue);
99
100
        return $object;
101
    }
102
103
    public function supportsNormalization($data, $format = null, array $context = []): bool
104
    {
105
        return $data instanceof ComponentPosition && !isset($context[self::ALREADY_CALLED]);
106
    }
107
108
    public function normalize($object, $format = null, array $context = [])
109
    {
110
        /* @var ComponentPosition $object */
111
        /* @var mixed|null        $format */
112
113
        $context[self::ALREADY_CALLED] = true;
114
115
        $context[MetadataNormalizer::METADATA_CONTEXT]['static_component'] = $object->component ? $this->iriConverter->getIriFromItem($object->component) : null;
116
        if ($object->pageDataProperty && (bool) $this->requestStack->getCurrentRequest()) {
117
            $object = $this->normalizeForPageData($object);
118
        }
119
120
        $component = $object->component;
121
        if ($component && $this->publishableStatusChecker->getAnnotationReader()->isConfigured($component) && $this->publishableStatusChecker->isGranted($component)) {
122
            $object->setComponent($this->normalizePublishableComponent($component));
123
        }
124
125
        return $this->normalizer->normalize($object, $format, $context);
126
    }
127
128
    private function normalizePublishableComponent(AbstractComponent $component)
129
    {
130
        $configuration = $this->publishableStatusChecker->getAnnotationReader()->getConfiguration($type = \get_class($component));
131
        $em = $this->registry->getManagerForClass(\get_class($component));
132
        if (!$em) {
133
            throw new InvalidArgumentException(sprintf('Could not find entity manager for class %s', $type));
134
        }
135
        /** @var ClassMetadataInfo $classMetadata */
136
        $classMetadata = $em->getClassMetadata($type);
137
        $draft = $classMetadata->getFieldValue($component, $configuration->reverseAssociationName);
138
139
        return $draft ?? $component;
140
    }
141
142
    private function normalizeForPageData(ComponentPosition $object): ComponentPosition
143
    {
144
        $pageData = $this->pageDataProvider->getPageData();
145
        if (!$pageData) {
146
            return $object;
147
            // Todo: causes a 500 error, perhaps we should look to return 404 and the front-end to handle this on server-side when it will not be admin then try again client-side
148
//            if ($object->component || $this->security->isGranted('ROLE_ADMIN')) {
149
//                return $object;
150
//            }
151
//            throw new UnexpectedValueException('Could not find page data for this route.');
152
        }
153
154
        $propertyAccessor = PropertyAccess::createPropertyAccessor();
155
        try {
156
            $component = $propertyAccessor->getValue($pageData, $object->pageDataProperty);
157
        } catch (UnexpectedTypeException | NoSuchIndexException $e) {
158
            return $object;
159
        }
160
161
        if (!$component) {
162
            // it is now optional to have the page data defined
163
            return $object;
164
            // throw new UnexpectedValueException(sprintf('Page data does not contain a value at %s', $object->pageDataProperty));
165
        }
166
167
        if (!$component instanceof AbstractComponent) {
168
            throw new InvalidArgumentException(sprintf('The page data property %s is not a component', $object->pageDataProperty));
169
        }
170
171
        $object->setComponent($component);
172
173
        return $object;
174
    }
175
}
176