Skip to content

Instantly share code, notes, and snippets.

@immutef
Created October 4, 2014 13:55
Show Gist options
  • Save immutef/1348c7b0505c53b04552 to your computer and use it in GitHub Desktop.
Save immutef/1348c7b0505c53b04552 to your computer and use it in GitHub Desktop.
Validation Exception Listener
<?php
namespace App\Listener\Exception;
use App\Exception\ValidationFailedException;
use JMS\DiExtraBundle\Annotation as DI;
use Symfony\Component\Console\Event\ConsoleExceptionEvent;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
/**
* @DI\Service("app.listen.exception.validation")
*
* @DI\Tag("kernel.event_listener", attributes={
* "event"="kernel.exception",
* "method"="onKernelException"
* })
*
* @DI\Tag("kernel.event_listener", attributes={
* "event"="console.exception",
* "method"="onConsoleException"
* })
*/
class ValidationFailedExceptionListener
{
/**
* @param ConsoleExceptionEvent $event
*/
public function onConsoleException(ConsoleExceptionEvent $event)
{
$exception = $event->getException();
if ($exception instanceof ValidationFailedException) {
$table = new Table($event->getOutput());
$table->setHeaders(['Property', 'Value', 'Message']);
foreach ($exception->getConstraintViolationList() as $violation) {
$table->addRow([
$violation->getPropertyPath(),
$violation->getInvalidValue(),
$violation->getMessage()
]);
}
$table->render();
}
}
/**
* @param GetResponseForExceptionEvent $event
*/
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
if ($exception instanceof ValidationFailedException) {
$violations = [];
foreach ($exception->getConstraintViolationList() as $violation) {
$violations[$violation->getPropertyPath()] = $violation->getMessage();
}
$event->setResponse(new JsonResponse($violations, 400));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment