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

[HttpKernel] Merge PartialDenormalizationException errors and validation errors together #50019

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
->args([
service('serializer'),
service('validator')->nullOnInvalid(),
service('translator')->nullOnInvalid(),
])
->tag('controller.targeted_value_resolver', ['name' => RequestPayloadValueResolver::class])

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,15 @@
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Serializer\Exception\NotEncodableValueException;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
use Symfony\Component\Serializer\Exception\PartialDenormalizationException;
use Symfony\Component\Serializer\Exception\UnsupportedFormatException;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Validator\ConstraintViolationInterface;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\Exception\ValidationFailedException;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

/**
* @author Konstantin Myakshin <molodchick@gmail.com>
Expand All @@ -51,7 +52,8 @@ final class RequestPayloadValueResolver implements ValueResolverInterface

public function __construct(
private readonly SerializerInterface&DenormalizerInterface $serializer,
private readonly ?ValidatorInterface $validator,
private readonly ?ValidatorInterface $validator = null,
private readonly ?TranslatorInterface $translator = null,
) {
}

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

try {
$payload = $this->$payloadMapper($request, $type, $attributes[0]);
} catch (PartialDenormalizationException $e) {
throw new HttpException($validationFailedCode, implode("\n", array_map(static fn (NotNormalizableValueException $e) => $e->getMessage(), $e->getErrors())), $e);
}

if (null !== $payload && \count($violations = $this->validator?->validate($payload) ?? [])) {
throw new HttpException($validationFailedCode, implode("\n", array_map(static fn (ConstraintViolationInterface $e) => $e->getMessage(), iterator_to_array($violations))), new ValidationFailedException($payload, $violations));
if ($this->validator) {
$violations = new ConstraintViolationList();
try {
$payload = $this->$payloadMapper($request, $type, $attributes[0]);
} catch (PartialDenormalizationException $e) {
$trans = $this->translator ? $this->translator->trans(...) : fn ($m, $p) => strtr($m, $p);
foreach ($e->getErrors() as $error) {
$parameters = ['{{ type }}' => implode('|', $error->getExpectedTypes())];
if ($error->canUseMessageForUser()) {
$parameters['hint'] = $error->getMessage();
}
$template = 'This value should be of type {{ type }}.';
$message = $trans($template, $parameters, 'validators');
$violations->add(new ConstraintViolation($message, $template, $parameters, null, $error->getPath(), null));
}
$payload = $e->getData();
}

if (null !== $payload) {
$violations->addAll($this->validator->validate($payload));
}

if (\count($violations)) {
throw new HttpException($validationFailedCode, implode("\n", array_map(static fn ($e) => $e->getMessage(), iterator_to_array($violations))), new ValidationFailedException($payload, $violations));
}
} else {
try {
$payload = $this->$payloadMapper($request, $type, $attributes[0]);
} catch (PartialDenormalizationException $e) {
throw new HttpException($validationFailedCode, implode("\n", array_map(static fn ($e) => $e->getMessage(), $e->getErrors())), $e);
}
}

if (null !== $payload || $argument->isNullable()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Exception\PartialDenormalizationException;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Validator\ConstraintViolation;
Expand Down Expand Up @@ -46,9 +47,29 @@ public function testNotTypedArgument()
$resolver->resolve($request, $argument);
}

public function testWithoutValidatorAndCouldNotDenormalize()
{
$content = '{"price": 50, "title": ["not a string"]}';
$serializer = new Serializer([new ObjectNormalizer()], ['json' => new JsonEncoder()]);

$resolver = new RequestPayloadValueResolver($serializer);

$argument = new ArgumentMetadata('invalid', RequestPayload::class, false, false, null, false, [
MapRequestPayload::class => new MapRequestPayload(),
]);
$request = Request::create('/', 'POST', server: ['CONTENT_TYPE' => 'application/json'], content: $content);

try {
$resolver->resolve($request, $argument);
$this->fail(sprintf('Expected "%s" to be thrown.', HttpException::class));
} catch (HttpException $e) {
$this->assertInstanceOf(PartialDenormalizationException::class, $e->getPrevious());
}
}

public function testValidationNotPassed()
{
$content = '{"price": 50}';
$content = '{"price": 50, "title": ["not a string"]}';
$payload = new RequestPayload(50);
$serializer = new Serializer([new ObjectNormalizer()], ['json' => new JsonEncoder()]);

Expand All @@ -69,15 +90,18 @@ public function testValidationNotPassed()
$resolver->resolve($request, $argument);
$this->fail(sprintf('Expected "%s" to be thrown.', HttpException::class));
} catch (HttpException $e) {
$this->assertInstanceOf(ValidationFailedException::class, $e->getPrevious());
$validationFailedException = $e->getPrevious();
$this->assertInstanceOf(ValidationFailedException::class, $validationFailedException);
$this->assertSame('This value should be of type unknown.', $validationFailedException->getViolations()[0]->getMessage());
$this->assertSame('Test', $validationFailedException->getViolations()[1]->getMessage());
}
}

public function testUnsupportedMedia()
{
$serializer = new Serializer();

$resolver = new RequestPayloadValueResolver($serializer, null);
$resolver = new RequestPayloadValueResolver($serializer);

$argument = new ArgumentMetadata('invalid', \stdClass::class, false, false, null, false, [
MapRequestPayload::class => new MapRequestPayload(),
Expand Down Expand Up @@ -161,6 +185,8 @@ public function testRequestInputValidationPassed()

class RequestPayload
{
public string $title;

public function __construct(public readonly float $price)
{
}
Expand Down
2 changes: 1 addition & 1 deletion 2 src/Symfony/Component/HttpKernel/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
"symfony/finder": "^5.4|^6.0",
"symfony/http-client-contracts": "^2.5|^3",
"symfony/process": "^5.4|^6.0",
"symfony/property-access": "^5.4|^6.0",
"symfony/property-access": "^5.4.5|^6.0.5",
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I need this patch

"symfony/routing": "^5.4|^6.0",
"symfony/serializer": "^6.3",
"symfony/stopwatch": "^5.4|^6.0",
Expand Down
Morty Proxy This is a proxified and sanitized view of the page, visit original site.