RequestPayloadValueResolver.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpKernel\Controller\ArgumentResolver;
  11. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\HttpKernel\Attribute\MapQueryString;
  15. use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
  16. use Symfony\Component\HttpKernel\Controller\ValueResolverInterface;
  17. use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
  18. use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
  19. use Symfony\Component\HttpKernel\Exception\HttpException;
  20. use Symfony\Component\HttpKernel\KernelEvents;
  21. use Symfony\Component\Serializer\Exception\NotEncodableValueException;
  22. use Symfony\Component\Serializer\Exception\PartialDenormalizationException;
  23. use Symfony\Component\Serializer\Exception\UnsupportedFormatException;
  24. use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
  25. use Symfony\Component\Serializer\SerializerInterface;
  26. use Symfony\Component\Validator\ConstraintViolation;
  27. use Symfony\Component\Validator\ConstraintViolationList;
  28. use Symfony\Component\Validator\Exception\ValidationFailedException;
  29. use Symfony\Component\Validator\Validator\ValidatorInterface;
  30. use Symfony\Contracts\Translation\TranslatorInterface;
  31. /**
  32. * @author Konstantin Myakshin <molodchick@gmail.com>
  33. *
  34. * @final
  35. */
  36. class RequestPayloadValueResolver implements ValueResolverInterface, EventSubscriberInterface
  37. {
  38. /**
  39. * @see DenormalizerInterface::COLLECT_DENORMALIZATION_ERRORS
  40. */
  41. private const CONTEXT_DENORMALIZE = [
  42. 'collect_denormalization_errors' => true,
  43. ];
  44. /**
  45. * @see DenormalizerInterface::COLLECT_DENORMALIZATION_ERRORS
  46. */
  47. private const CONTEXT_DESERIALIZE = [
  48. 'collect_denormalization_errors' => true,
  49. ];
  50. public function __construct(
  51. private readonly SerializerInterface&DenormalizerInterface $serializer,
  52. private readonly ?ValidatorInterface $validator = null,
  53. private readonly ?TranslatorInterface $translator = null,
  54. ) {
  55. }
  56. public function resolve(Request $request, ArgumentMetadata $argument): iterable
  57. {
  58. $attribute = $argument->getAttributesOfType(MapQueryString::class, ArgumentMetadata::IS_INSTANCEOF)[0]
  59. ?? $argument->getAttributesOfType(MapRequestPayload::class, ArgumentMetadata::IS_INSTANCEOF)[0]
  60. ?? null;
  61. if (!$attribute) {
  62. return [];
  63. }
  64. if ($argument->isVariadic()) {
  65. throw new \LogicException(\sprintf('Mapping variadic argument "$%s" is not supported.', $argument->getName()));
  66. }
  67. $attribute->metadata = $argument;
  68. return [$attribute];
  69. }
  70. public function onKernelControllerArguments(ControllerArgumentsEvent $event): void
  71. {
  72. $arguments = $event->getArguments();
  73. foreach ($arguments as $i => $argument) {
  74. if ($argument instanceof MapQueryString) {
  75. $payloadMapper = 'mapQueryString';
  76. $validationFailedCode = $argument->validationFailedStatusCode;
  77. } elseif ($argument instanceof MapRequestPayload) {
  78. $payloadMapper = 'mapRequestPayload';
  79. $validationFailedCode = $argument->validationFailedStatusCode;
  80. } else {
  81. continue;
  82. }
  83. $request = $event->getRequest();
  84. if (!$type = $argument->metadata->getType()) {
  85. throw new \LogicException(\sprintf('Could not resolve the "$%s" controller argument: argument should be typed.', $argument->metadata->getName()));
  86. }
  87. if ($this->validator) {
  88. $violations = new ConstraintViolationList();
  89. try {
  90. $payload = $this->$payloadMapper($request, $type, $argument);
  91. } catch (PartialDenormalizationException $e) {
  92. $trans = $this->translator ? $this->translator->trans(...) : fn ($m, $p) => strtr($m, $p);
  93. foreach ($e->getErrors() as $error) {
  94. $parameters = [];
  95. $template = 'This value was of an unexpected type.';
  96. if ($expectedTypes = $error->getExpectedTypes()) {
  97. $template = 'This value should be of type {{ type }}.';
  98. $parameters['{{ type }}'] = implode('|', $expectedTypes);
  99. }
  100. if ($error->canUseMessageForUser()) {
  101. $parameters['hint'] = $error->getMessage();
  102. }
  103. $message = $trans($template, $parameters, 'validators');
  104. $violations->add(new ConstraintViolation($message, $template, $parameters, null, $error->getPath(), null));
  105. }
  106. $payload = $e->getData();
  107. }
  108. if (null !== $payload && !\count($violations)) {
  109. $violations->addAll($this->validator->validate($payload, null, $argument->validationGroups ?? null));
  110. }
  111. if (\count($violations)) {
  112. throw new HttpException($validationFailedCode, implode("\n", array_map(static fn ($e) => $e->getMessage(), iterator_to_array($violations))), new ValidationFailedException($payload, $violations));
  113. }
  114. } else {
  115. try {
  116. $payload = $this->$payloadMapper($request, $type, $argument);
  117. } catch (PartialDenormalizationException $e) {
  118. throw new HttpException($validationFailedCode, implode("\n", array_map(static fn ($e) => $e->getMessage(), $e->getErrors())), $e);
  119. }
  120. }
  121. if (null === $payload) {
  122. $payload = match (true) {
  123. $argument->metadata->hasDefaultValue() => $argument->metadata->getDefaultValue(),
  124. $argument->metadata->isNullable() => null,
  125. default => throw new HttpException($validationFailedCode),
  126. };
  127. }
  128. $arguments[$i] = $payload;
  129. }
  130. $event->setArguments($arguments);
  131. }
  132. public static function getSubscribedEvents(): array
  133. {
  134. return [
  135. KernelEvents::CONTROLLER_ARGUMENTS => 'onKernelControllerArguments',
  136. ];
  137. }
  138. private function mapQueryString(Request $request, string $type, MapQueryString $attribute): ?object
  139. {
  140. if (!$data = $request->query->all()) {
  141. return null;
  142. }
  143. return $this->serializer->denormalize($data, $type, 'csv', $attribute->serializationContext + self::CONTEXT_DENORMALIZE);
  144. }
  145. private function mapRequestPayload(Request $request, string $type, MapRequestPayload $attribute): ?object
  146. {
  147. if (null === $format = $request->getContentTypeFormat()) {
  148. throw new HttpException(Response::HTTP_UNSUPPORTED_MEDIA_TYPE, 'Unsupported format.');
  149. }
  150. if ($attribute->acceptFormat && !\in_array($format, (array) $attribute->acceptFormat, true)) {
  151. throw new HttpException(Response::HTTP_UNSUPPORTED_MEDIA_TYPE, \sprintf('Unsupported format, expects "%s", but "%s" given.', implode('", "', (array) $attribute->acceptFormat), $format));
  152. }
  153. if ($data = $request->request->all()) {
  154. return $this->serializer->denormalize($data, $type, 'csv', $attribute->serializationContext + self::CONTEXT_DENORMALIZE);
  155. }
  156. if ('' === $data = $request->getContent()) {
  157. return null;
  158. }
  159. if ('form' === $format) {
  160. throw new HttpException(Response::HTTP_BAD_REQUEST, 'Request payload contains invalid "form" data.');
  161. }
  162. try {
  163. return $this->serializer->deserialize($data, $type, $format, self::CONTEXT_DESERIALIZE + $attribute->serializationContext);
  164. } catch (UnsupportedFormatException $e) {
  165. throw new HttpException(Response::HTTP_UNSUPPORTED_MEDIA_TYPE, \sprintf('Unsupported format: "%s".', $format), $e);
  166. } catch (NotEncodableValueException $e) {
  167. throw new HttpException(Response::HTTP_BAD_REQUEST, \sprintf('Request payload contains invalid "%s" data.', $format), $e);
  168. }
  169. }
  170. }