|
16 | 16 | use ApiPlatform\Api\FormatMatcher;
|
17 | 17 | use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
|
18 | 18 | use ApiPlatform\Serializer\SerializerContextBuilderInterface;
|
| 19 | +use ApiPlatform\Symfony\Validator\Exception\ValidationException; |
19 | 20 | use ApiPlatform\Util\OperationRequestInitiatorTrait;
|
20 | 21 | use ApiPlatform\Util\RequestAttributesExtractor;
|
21 | 22 | use Symfony\Component\HttpFoundation\Request;
|
22 | 23 | use Symfony\Component\HttpKernel\Event\RequestEvent;
|
23 | 24 | use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
|
| 25 | +use Symfony\Component\Serializer\Exception\NotNormalizableValueException; |
| 26 | +use Symfony\Component\Serializer\Exception\PartialDenormalizationException; |
24 | 27 | use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
|
25 | 28 | use Symfony\Component\Serializer\SerializerInterface;
|
| 29 | +use Symfony\Component\Validator\ConstraintViolation; |
| 30 | +use Symfony\Component\Validator\ConstraintViolationList; |
26 | 31 |
|
27 | 32 | /**
|
28 | 33 | * Updates the entity retrieved by the data provider with data contained in the request body.
|
@@ -72,11 +77,28 @@ public function onKernelRequest(RequestEvent $event): void
|
72 | 77 | if (null !== $data) {
|
73 | 78 | $context[AbstractNormalizer::OBJECT_TO_POPULATE] = $data;
|
74 | 79 | }
|
75 |
| - |
76 |
| - $request->attributes->set( |
77 |
| - 'data', |
78 |
| - $this->serializer->deserialize($request->getContent(), $context['resource_class'], $format, $context) |
79 |
| - ); |
| 80 | + try { |
| 81 | + $request->attributes->set( |
| 82 | + 'data', |
| 83 | + $this->serializer->deserialize($request->getContent(), $context['resource_class'], $format, $context) |
| 84 | + ); |
| 85 | + } catch (PartialDenormalizationException $e) { |
| 86 | + $violations = new ConstraintViolationList(); |
| 87 | + foreach ($e->getErrors() as $exception) { |
| 88 | + if (!$exception instanceof NotNormalizableValueException) { |
| 89 | + continue; |
| 90 | + } |
| 91 | + $message = sprintf('The type of the "%s" attribute must be "%s", "%s" given.', $exception->getPath(), implode(', ', $exception->getExpectedTypes() ?? []), $exception->getCurrentType()); |
| 92 | + $parameters = []; |
| 93 | + if ($exception->canUseMessageForUser()) { |
| 94 | + $parameters['hint'] = $exception->getMessage(); |
| 95 | + } |
| 96 | + $violations->add(new ConstraintViolation($message, '', $parameters, null, $exception->getPath(), null, null, (string) $exception->getCode())); |
| 97 | + } |
| 98 | + if (0 !== \count($violations)) { |
| 99 | + throw new ValidationException($violations); |
| 100 | + } |
| 101 | + } |
80 | 102 | }
|
81 | 103 |
|
82 | 104 | /**
|
|
0 commit comments