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

api-platform / core / 9562658349

18 Jun 2024 09:35AM UTC coverage: 62.637% (+0.4%) from 62.272%
9562658349

push

github

soyuka
Merge 3.4

52 of 55 new or added lines in 6 files covered. (94.55%)

236 existing lines in 20 files now uncovered.

11016 of 17587 relevant lines covered (62.64%)

60.45 hits per line

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

56.1
/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\Serializer\SerializerContextBuilderInterface as LegacySerializerContextBuilderInterface;
19
use ApiPlatform\State\ProviderInterface;
20
use ApiPlatform\State\SerializerContextBuilderInterface;
21
use ApiPlatform\Validator\Exception\ValidationException;
22
use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
23
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
24
use Symfony\Component\Serializer\Exception\PartialDenormalizationException;
25
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
26
use Symfony\Component\Serializer\SerializerInterface;
27
use Symfony\Component\Validator\Constraints\Type;
28
use Symfony\Component\Validator\ConstraintViolation;
29
use Symfony\Component\Validator\ConstraintViolationList;
30
use Symfony\Contracts\Translation\LocaleAwareInterface;
31
use Symfony\Contracts\Translation\TranslatorInterface;
32
use Symfony\Contracts\Translation\TranslatorTrait;
33

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

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

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

59
        if (!$operation->canDeserialize()) {
304✔
60
            return $data;
288✔
61
        }
62

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

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

73
        $serializerContext['uri_variables'] = $uriVariables;
12✔
74

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

79
        $method = $operation->getMethod();
12✔
80

81
        if (
82
            null !== $data
12✔
83
            && (
84
                'POST' === $method
12✔
85
                || 'PATCH' === $method
12✔
86
                || ('PUT' === $method && !($operation->getExtraProperties()['standard_put'] ?? false))
12✔
87
            )
88
        ) {
89
            $serializerContext[AbstractNormalizer::OBJECT_TO_POPULATE] = $data;
×
90
        }
91

92
        try {
93
            return $this->serializer->deserialize((string) $request->getContent(), $operation->getClass(), $format, $serializerContext);
12✔
94
        } catch (PartialDenormalizationException $e) {
×
95
            if (!class_exists(ConstraintViolationList::class)) {
×
96
                throw $e;
×
97
            }
98

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

UNCOV
116
        return $data;
×
117
    }
118
}
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