8000 [HttpKernel] Customise error code on validation error occurred in #[MapRequestPayload] by siketyan · Pull Request #50993 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[HttpKernel] Customise error code on validation error occurred in #[MapRequestPayload] #50993

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

Closed
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
1 change: 1 addition & 0 deletions src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ CHANGELOG
---

* Add native return type to `Translator` and to `Application::reset()`
* Allow customizing HTTP status code on validation error occurred in `#[MapRequestPayload]`

6.3
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,15 @@ public function getConfigTreeBuilder(): TreeBuilder
->defaultValue('error_controller')
->end()
->booleanNode('handle_all_throwables')->info('HttpKernel will handle all kinds of \Throwable')->end()
->arrayNode('map_request_payload')
->addDefaultsIfNotSet()
->children()
->scalarNode('status_code_on_error')
Copy link
Contributor

Choose a reason for hiding this comment

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

is there a usecase that requires a different default?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

As described in #50992, sometimes we want use 400 instead of 422 in application-global. So this configuration node supports to change the HTTP status code on error globally.

Copy link
Contributor Author
< 8000 /h3>

Choose a reason for hiding this comment

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

BTW, this is actually dupe of #50767, so I'll close this pull request now.

->info('HTTP status code to be returned on error occurred while parsing the request payload.')
->defaultNull()
->end()
->end()
->end()
->end()
;

Expand Down
8000
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,7 @@ public function load(array $configs, ContainerBuilder $container)
$container->getDefinition('locale_listener')->replaceArgument(3, $config['set_locale_from_accept_language']);
$container->getDefinition('response_listener')->replaceArgument(1, $config['set_content_language_from_locale']);
$container->getDefinition('http_kernel')->replaceArgument(4, $config['handle_all_throwables'] ?? false);
$container->getDefinition('argument_resolver.request_payload')->replaceArgument(3, $config['map_request_payload']['status_code_on_error']);

// If the slugger is used but the String component is not available, we should throw an error
if (!ContainerBuilder::willBeAvailable('symfony/string', SluggerInterface::class, ['symfony/framework-bundle'])) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
service('serializer'),
service('validator')->nullOnInvalid(),
service('translator')->nullOnInvalid(),
abstract_arg('The "map_request_payload.status_code_on_error" config value'),
])
->tag('controller.targeted_value_resolver', ['name' => RequestPayloadValueResolver::class])
->tag('kernel.event_subscriber')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -739,6 +739,9 @@ class_exists(SemaphoreStore::class) && SemaphoreStore::isSupported() ? 'semaphor
'remote-event' => [
'enabled' => false,
],
'map_request_payload' => [
'status_code_on_error' => null,
],
];
}
}
6D40
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,24 @@ public static function mapRequestPayloadProvider(): iterable
'expectedStatusCode' => 422,
];
}

public function testMapRequestPayloadError400()
{
$client = self::createClient(['test_case' => 'ApiAttributesTest']);

$client->request(
'POST',
'/map-request-body-error-400',
[],
[],
['HTTP_ACCEPT' => 'application/json', 'CONTENT_TYPE' => 'application/json'],
json_encode([]),
);

$response = $client->getResponse();

self::assertSame(Response::HTTP_BAD_REQUEST, $response->getStatusCode());
}
}

class WithMapQueryStringController
Expand Down Expand Up @@ -388,6 +406,16 @@ public function __invoke(#[MapRequestPayload] ?RequestBody $body, Request $reque
}
}

class WithMapRequestPayloadError400Controller
{
public function __invoke(
#[MapRequestPayload(statusCodeOnError: Response::HTTP_BAD_REQUEST)] ?RequestBody $body,
Request $request,
): Response {
return new Response('', Response::HTTP_NO_CONTENT);
}
}

class QueryString
{
public function __construct(
Expand Down
9E88
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,7 @@ map_query_string:
map_request_body:
path: /map-request-body.{_format}
controller: Symfony\Bundle\FrameworkBundle\Tests\Functional\WithMapRequestPayloadController

map_request_body_error_400:
path: /map-request-body-error-400
controller: Symfony\Bundle\FrameworkBundle\Tests\Functional\WithMapRequestPayloadError400Controller
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public function __construct(
public readonly array $serializationContext = [],
public readonly string|GroupSequence|array|null $validationGroups = null,
string $resolver = RequestPayloadValueResolver::class,
public readonly ?int $statusCodeOnError = null,
) {
parent::__construct($resolver);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ public function __construct(
private readonly SerializerInterface&DenormalizerInterface $serializer,
private readonly ?ValidatorInterface $validator = null,
private readonly ?TranslatorInterface $translator = null,
private readonly ?int $statusCodeOnError = null,
) {
}

Expand Down Expand Up @@ -91,7 +92,9 @@ public function onKernelControllerArguments(ControllerArgumentsEvent $event): vo
$validationFailedCode = Response::HTTP_NOT_FOUND;
} elseif ($argument instanceof MapRequestPayload) {
$payloadMapper = 'mapRequestPayload';
$validationFailedCode = Response::HTTP_UNPROCESSABLE_ENTITY;
$validationFailedCode = $argument->statusCodeOnError
?? $this->statusCodeOnError
?? Response::HTTP_UNPROCESSABLE_ENTITY;
} else {
continue;
}
Expand Down
0