|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <[email protected]> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Symfony\Component\HttpKernel\EventListener; |
| 13 | + |
| 14 | +use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
| 15 | +use Symfony\Component\HttpKernel\Event\ExceptionEvent; |
| 16 | +use Symfony\Component\HttpKernel\KernelEvents; |
| 17 | +use Symfony\Component\Serializer\Exception\NotNormalizableValueException; |
| 18 | +use Symfony\Component\Serializer\Exception\PartialDenormalizationException; |
| 19 | +use Symfony\Component\Validator\ConstraintViolation; |
| 20 | +use Symfony\Component\Validator\ConstraintViolationList; |
| 21 | +use Symfony\Component\Validator\Exception\ValidationFailedException; |
| 22 | + |
| 23 | +/** |
| 24 | + * @author Konstantin Myakshin <[email protected]> |
| 25 | + */ |
| 26 | +final class PartialDenormalizationExceptionListener implements EventSubscriberInterface |
| 27 | +{ |
| 28 | + public function onKernelException(ExceptionEvent $event): void |
| 29 | + { |
| 30 | + $throwable = $event->getThrowable(); |
| 31 | + |
| 32 | + if (!$throwable instanceof PartialDenormalizationException) { |
| 33 | + return; |
| 34 | + } |
| 35 | + |
| 36 | + $violations = new ConstraintViolationList(); |
| 37 | + /** @var NotNormalizableValueException $exception */ |
| 38 | + foreach ($throwable->getErrors() as $exception) { |
| 39 | + //fixme: how to translate this messages? |
| 40 | + $message = sprintf( |
| 41 | + 'The type must be one of "%s" ("%s" given).', |
| 42 | + implode(', ', $exception->getExpectedTypes()), |
| 43 | + $exception->getCurrentType() |
| 44 | + ); |
| 45 | + $parameters = []; |
| 46 | + if ($exception->canUseMessageForUser()) { |
| 47 | + $parameters['hint'] = $exception->getMessage(); |
| 48 | + } |
| 49 | + $violations->add(new ConstraintViolation($message, '', $parameters, null, $exception->getPath(), null)); |
| 50 | + } |
| 51 | + |
| 52 | + $event->setThrowable(new ValidationFailedException($throwable->getData(), $violations, $throwable)); |
| 53 | + } |
| 54 | + |
| 55 | + public static function getSubscribedEvents(): array |
| 56 | + { |
| 57 | + return [ |
| 58 | + KernelEvents::EXCEPTION => ['onKernelException', -16], |
| 59 | + ]; |
| 60 | + } |
| 61 | +} |
0 commit comments