Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 7301ea9

Browse filesBrowse files
committed
[HttpKernel] Merge PartialDenormalizationException errors and validation errors together
1 parent e738a6c commit 7301ea9
Copy full SHA for 7301ea9

File tree

3 files changed

+70
-12
lines changed
Filter options

3 files changed

+70
-12
lines changed

‎src/Symfony/Bundle/FrameworkBundle/Resources/config/web.php

Copy file name to clipboardExpand all lines: src/Symfony/Bundle/FrameworkBundle/Resources/config/web.php
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@
6666
->args([
6767
service('serializer'),
6868
service('validator')->nullOnInvalid(),
69+
service('translator')->nullOnInvalid(),
6970
])
7071
->tag('controller.targeted_value_resolver', ['name' => RequestPayloadValueResolver::class])
7172

‎src/Symfony/Component/HttpKernel/Controller/ArgumentResolver/RequestPayloadValueResolver.php

Copy file name to clipboardExpand all lines: src/Symfony/Component/HttpKernel/Controller/ArgumentResolver/RequestPayloadValueResolver.php
+40-9Lines changed: 40 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,18 +15,22 @@
1515
use Symfony\Component\HttpFoundation\Response;
1616
use Symfony\Component\HttpKernel\Attribute\MapQueryString;
1717
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
18-
use Symfony\Component\HttpKernel\Controller\ValueResolverInterface;
1918
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
19+
use Symfony\Component\HttpKernel\Controller\ValueResolverInterface;
2020
use Symfony\Component\HttpKernel\Exception\HttpException;
2121
use Symfony\Component\Serializer\Exception\NotEncodableValueException;
2222
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
2323
use Symfony\Component\Serializer\Exception\PartialDenormalizationException;
2424
use Symfony\Component\Serializer\Exception\UnsupportedFormatException;
2525
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
2626
use Symfony\Component\Serializer\SerializerInterface;
27+
use Symfony\Component\Translation\IdentityTranslator;
28+
use Symfony\Component\Validator\ConstraintViolation;
2729
use Symfony\Component\Validator\ConstraintViolationInterface;
30+
use Symfony\Component\Validator\ConstraintViolationList;
2831
use Symfony\Component\Validator\Exception\ValidationFailedException;
2932
use Symfony\Component\Validator\Validator\ValidatorInterface;
33+
use Symfony\Contracts\Translation\TranslatorInterface;
3034

3135
/**
3236
* @author Konstantin Myakshin <molodchick@gmail.com>
@@ -52,6 +56,7 @@ final class RequestPayloadValueResolver implements ValueResolverInterface
5256
public function __construct(
5357
private readonly SerializerInterface&DenormalizerInterface $serializer,
5458
private readonly ?ValidatorInterface $validator,
59+
private readonly ?TranslatorInterface $translator = new IdentityTranslator(),
5560
) {
5661
}
5762

@@ -71,14 +76,40 @@ public function resolve(Request $request, ArgumentMetadata $argument): iterable
7176
throw new \LogicException(sprintf('Could not resolve the "$%s" controller argument: argument should be typed.', $argument->getName()));
7277
}
7378

74-
try {
75-
$payload = $this->$payloadMapper($request, $type, $attributes[0]);
76-
} catch (PartialDenormalizationException $e) {
77-
throw new HttpException($validationFailedCode, implode("\n", array_map(static fn (NotNormalizableValueException $e) => $e->getMessage(), $e->getErrors())), $e);
78-
}
79-
80-
if (null !== $payload && \count($violations = $this->validator?->validate($payload) ?? [])) {
81-
throw new HttpException($validationFailedCode, implode("\n", array_map(static fn (ConstraintViolationInterface $e) => $e->getMessage(), iterator_to_array($violations))), new ValidationFailedException($payload, $violations));
79+
if ($this->validator) {
80+
$violations = new ConstraintViolationList();
81+
try {
82+
$payload = $this->$payloadMapper($request, $type, $attributes[0]);
83+
} catch (PartialDenormalizationException $exception) {
84+
if (!$this->validator) {
85+
throw $exception;
86+
}
87+
foreach ($exception->getErrors() as $error) {
88+
$parameters = ['{{ type }}' => implode('|', $error->getExpectedTypes())];
89+
$message = 'This value should be of type {{ type }}.';
90+
$message = $this->translator->trans('This value should be of type {{ type }}.', $parameters);
91+
92+
if ($error->canUseMessageForUser()) {
93+
$parameters['hint'] = $error->getMessage();
94+
}
95+
$violations->add(new ConstraintViolation($message, '', $parameters, null, $error->getPath(), null));
96+
}
97+
$payload = $exception->getData();
98+
}
99+
100+
if (null !== $payload && $this->validator) {
101+
$violations->addAll($this->validator->validate($payload));
102+
}
103+
104+
if (\count($violations)) {
105+
throw new HttpException($validationFailedCode, implode("\n", array_map(static fn (ConstraintViolationInterface $e) => $e->getMessage(), iterator_to_array($violations))), new ValidationFailedException($payload, $violations));
106+
}
107+
} else {
108+
try {
109+
$payload = $this->$payloadMapper($request, $type, $attributes[0]);
110+
} catch (PartialDenormalizationException $exception) {
111+
throw new HttpException($validationFailedCode, implode("\n", array_map(static fn (NotNormalizableValueException $e) => $e->getMessage(), $exception->getErrors())), $exception);
112+
}
82113
}
83114

84115
if (null !== $payload || $argument->isNullable()) {

‎src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolver/RequestPayloadValueResolverTest.php

Copy file name to clipboardExpand all lines: src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolver/RequestPayloadValueResolverTest.php
+29-3Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,11 @@
1515
use Symfony\Component\HttpFoundation\Request;
1616
use Symfony\Component\HttpKernel\Attribute\MapQueryString;
1717
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
18-
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\RequestPayloadValueResolver;
1918
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
19+
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\RequestPayloadValueResolver;
2020
use Symfony\Component\HttpKernel\Exception\HttpException;
2121
use Symfony\Component\Serializer\Encoder\JsonEncoder;
22+
use Symfony\Component\Serializer\Exception\PartialDenormalizationException;
2223
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
2324
use Symfony\Component\Serializer\Serializer;
2425
use Symfony\Component\Validator\ConstraintViolation;
@@ -46,9 +47,29 @@ public function testNotTypedArgument()
4647
$resolver->resolve($request, $argument);
4748
}
4849

50+
public function testWithoutValidatorAndCouldNotDenormalize()
51+
{
52+
$content = '{"price": 50, "title": ["not a string"]}';
53+
$serializer = new Serializer([new ObjectNormalizer()], ['json' => new JsonEncoder()]);
54+
55+
$resolver = new RequestPayloadValueResolver($serializer, null);
56+
57+
$argument = new ArgumentMetadata('invalid', RequestPayload::class, false, false, null, false, [
58+
MapRequestPayload::class => new MapRequestPayload(),
59+
]);
60+
$request = Request::create('/', 'POST', server: ['CONTENT_TYPE' => 'application/json'], content: $content);
61+
62+
try {
63+
$resolver->resolve($request, $argument);
64+
$this->fail(sprintf('Expected "%s" to be thrown.', HttpException::class));
65+
} catch (HttpException $e) {
66+
$this->assertInstanceOf(PartialDenormalizationException::class, $e->getPrevious());
67+
}
68+
}
69+
4970
public function testValidationNotPassed()
5071
{
51-
$content = '{"price": 50}';
72+
$content = '{"price": 50, "title": ["not a string"]}';
5273
$payload = new RequestPayload(50);
5374
$serializer = new Serializer([new ObjectNormalizer()], ['json' => new JsonEncoder()]);
5475

@@ -69,7 +90,10 @@ public function testValidationNotPassed()
6990
$resolver->resolve($request, $argument);
7091
$this->fail(sprintf('Expected "%s" to be thrown.', HttpException::class));
7192
} catch (HttpException $e) {
72-
$this->assertInstanceOf(ValidationFailedException::class, $e->getPrevious());
93+
$validationFailedException = $e->getPrevious();
94+
$this->assertInstanceOf(ValidationFailedException::class, $validationFailedException);
95+
$this->assertSame('This value should be of type unknown.', $validationFailedException->getViolations()[0]->getMessage());
96+
$this->assertSame('Test', $validationFailedException->getViolations()[1]->getMessage());
7397
}
7498
}
7599

@@ -161,6 +185,8 @@ public function testRequestInputValidationPassed()
161185

162186
class RequestPayload
163187
{
188+
public string $title;
189+
164190
public function __construct(public readonly float $price)
165191
{
166192
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.