Skip to content

Commit

Permalink
feat: invalid form returns http 422
Browse files Browse the repository at this point in the history
Fixes sulu#383
  • Loading branch information
Jupi007 authored and alexander-schranz committed Jul 24, 2024
1 parent 91b7157 commit a393b9d
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
33 changes: 32 additions & 1 deletion Event/RequestListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@
use Sulu\Bundle\FormBundle\Form\HandlerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;

class RequestListener
{
Expand All @@ -41,6 +43,14 @@ class RequestListener
*/
protected $eventDispatcher;

/**
* Flag set to true when an invalid form is submitted,
* so we can set the http return code to 422.
*
* @var bool
*/
protected $invalidSubmittedForm = false;

/**
* RequestListener constructor.
*/
Expand Down Expand Up @@ -73,10 +83,16 @@ public function onKernelRequest(RequestEvent $event): void
try {
$form = $this->formBuilder->buildByRequest($request);

if (!$form || !$form->isSubmitted() || !$form->isValid()) {
if (!$form || !$form->isSubmitted()) {
// do nothing when no form was found or not valid
return;
}

if ($form && $form->isSubmitted() && !$form->isValid()) {
$this->invalidSubmittedForm = true;

return;
}
} catch (\Exception $e) {
// Catch all exception on build form by request
return;
Expand All @@ -96,4 +112,19 @@ public function onKernelRequest(RequestEvent $event): void
$event->setResponse($response);
}
}

public function onKernelResponse(ResponseEvent $event): void
{
if (\method_exists($event, 'isMainRequest') ? !$event->isMainRequest() : !$event->isMasterRequest()) {
// do nothing if it's not the master request
return;
}

if ($this->invalidSubmittedForm) {
$response = $event->getResponse() ?? new Response();
$response->setStatusCode(Response::HTTP_UNPROCESSABLE_ENTITY);

$event->setResponse($response);
}
}
}
1 change: 1 addition & 0 deletions Resources/config/services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@
<argument type="service" id="event_dispatcher" />

<tag name="kernel.event_listener" event="kernel.request" method="onKernelRequest" />
<tag name="kernel.event_listener" event="kernel.response" method="onKernelResponse" />
</service>

<!-- List Builder -->
Expand Down

0 comments on commit a393b9d

Please sign in to comment.