• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

api-platform / core / 15394793169

02 Jun 2025 02:22PM UTC coverage: 21.851% (-0.03%) from 21.877%
15394793169

push

github

web-flow
chore: use type-info:^7.3 (#7185)

0 of 168 new or added lines in 12 files covered. (0.0%)

15 existing lines in 7 files now uncovered.

11381 of 52084 relevant lines covered (21.85%)

10.6 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

69.09
/src/State/Provider/DeserializeProvider.php
1
<?php
2

3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <dunglas@gmail.com>
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 ApiPlatform\State\Provider;
15

16
use ApiPlatform\Metadata\HttpOperation;
17
use ApiPlatform\Metadata\Operation;
18
use ApiPlatform\State\ProviderInterface;
19
use ApiPlatform\State\SerializerContextBuilderInterface;
20
use ApiPlatform\Validator\Exception\ValidationException;
21
use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
22
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
23
use Symfony\Component\Serializer\Exception\PartialDenormalizationException;
24
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
25
use Symfony\Component\Serializer\SerializerInterface;
26
use Symfony\Component\Validator\Constraints\Type;
27
use Symfony\Component\Validator\ConstraintViolation;
28
use Symfony\Component\Validator\ConstraintViolationList;
29
use Symfony\Contracts\Translation\LocaleAwareInterface;
30
use Symfony\Contracts\Translation\TranslatorInterface;
31
use Symfony\Contracts\Translation\TranslatorTrait;
32

33
final class DeserializeProvider implements ProviderInterface
34
{
35
    public function __construct(
36
        private readonly ?ProviderInterface $decorated,
37
        private readonly SerializerInterface $serializer,
38
        private readonly SerializerContextBuilderInterface $serializerContextBuilder,
39
        private ?TranslatorInterface $translator = null,
40
    ) {
41
        if (null === $this->translator) {
241✔
42
            $this->translator = new class implements TranslatorInterface, LocaleAwareInterface {
×
43
                use TranslatorTrait;
44
            };
×
45
            $this->translator->setLocale('en');
×
46
        }
47
    }
48

49
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
50
    {
51
        // We need request content
52
        if (!$operation instanceof HttpOperation || !($request = $context['request'] ?? null)) {
8✔
53
            return $this->decorated?->provide($operation, $uriVariables, $context);
×
54
        }
55

56
        $data = $this->decorated ? $this->decorated->provide($operation, $uriVariables, $context) : $request->attributes->get('data');
8✔
57

58
        if (!$operation->canDeserialize()) {
8✔
UNCOV
59
            return $data;
×
60
        }
61

62
        $contentType = $request->headers->get('CONTENT_TYPE');
8✔
63
        if (null === $contentType || '' === $contentType) {
8✔
64
            throw new UnsupportedMediaTypeHttpException('The "Content-Type" header must exist.');
×
65
        }
66

67
        $serializerContext = $this->serializerContextBuilder->createFromRequest($request, false, [
8✔
68
            'resource_class' => $operation->getClass(),
8✔
69
            'operation' => $operation,
8✔
70
        ]);
8✔
71

72
        $serializerContext['uri_variables'] = $uriVariables;
8✔
73

74
        if (!$format = $request->attributes->get('input_format') ?? null) {
8✔
75
            throw new UnsupportedMediaTypeHttpException('Format not supported.');
×
76
        }
77

78
        if ($operation instanceof HttpOperation && null === ($serializerContext[SerializerContextBuilderInterface::ASSIGN_OBJECT_TO_POPULATE] ?? null)) {
8✔
79
            $method = $operation->getMethod();
×
80
            $assignObjectToPopulate = 'POST' === $method
×
81
                || 'PATCH' === $method
×
82
                || ('PUT' === $method && !($operation->getExtraProperties()['standard_put'] ?? true));
×
83

84
            if ($assignObjectToPopulate) {
×
85
                $serializerContext[SerializerContextBuilderInterface::ASSIGN_OBJECT_TO_POPULATE] = true;
×
86
                trigger_deprecation('api-platform/core', '5.0', 'To assign an object to populate you should set "%s" in your denormalizationContext, not defining it is deprecated.', SerializerContextBuilderInterface::ASSIGN_OBJECT_TO_POPULATE);
×
87
            }
88
        }
89

90
        if (null !== $data && ($serializerContext[SerializerContextBuilderInterface::ASSIGN_OBJECT_TO_POPULATE] ?? false)) {
8✔
91
            $serializerContext[AbstractNormalizer::OBJECT_TO_POPULATE] = $data;
1✔
92
        }
93

94
        unset($serializerContext[SerializerContextBuilderInterface::ASSIGN_OBJECT_TO_POPULATE]);
8✔
95

96
        try {
97
            return $this->serializer->deserialize((string) $request->getContent(), $serializerContext['deserializer_type'] ?? $operation->getClass(), $format, $serializerContext);
8✔
98
        } catch (PartialDenormalizationException $e) {
2✔
99
            if (!class_exists(ConstraintViolationList::class)) {
1✔
100
                throw $e;
×
101
            }
102

103
            $violations = new ConstraintViolationList();
1✔
104
            foreach ($e->getErrors() as $exception) {
1✔
105
                if (!$exception instanceof NotNormalizableValueException) {
1✔
106
                    continue;
×
107
                }
108
                $expectedTypes = $this->normalizeExpectedTypes($exception->getExpectedTypes());
1✔
109
                $message = (new Type($expectedTypes))->message;
1✔
110
                $parameters = [];
1✔
111
                if ($exception->canUseMessageForUser()) {
1✔
112
                    $parameters['hint'] = $exception->getMessage();
1✔
113
                }
114
                $violations->add(new ConstraintViolation($this->translator->trans($message, ['{{ type }}' => implode('|', $expectedTypes)], 'validators'), $message, $parameters, null, $exception->getPath(), null, null, (string) Type::INVALID_TYPE_ERROR));
1✔
115
            }
116
            if (0 !== \count($violations)) {
1✔
117
                throw new ValidationException($violations);
1✔
118
            }
119
        }
120

121
        return $data;
×
122
    }
123

124
    private function normalizeExpectedTypes(?array $expectedTypes = null): array
125
    {
126
        $normalizedTypes = [];
1✔
127

128
        foreach ($expectedTypes ?? [] as $expectedType) {
1✔
129
            $normalizedType = $expectedType;
1✔
130

131
            if (class_exists($expectedType) || interface_exists($expectedType)) {
1✔
132
                $classReflection = new \ReflectionClass($expectedType);
1✔
133
                $normalizedType = $classReflection->getShortName();
1✔
134
            }
135

136
            $normalizedTypes[] = $normalizedType;
1✔
137
        }
138

139
        return $normalizedTypes;
1✔
140
    }
141
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc