RequestPayloadValueResolver.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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\File\UploadedFile;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpKernel\Attribute\MapQueryString;
  15. use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
  16. use Symfony\Component\HttpKernel\Attribute\MapUploadedFile;
  17. use Symfony\Component\HttpKernel\Controller\ValueResolverInterface;
  18. use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
  19. use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
  20. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  21. use Symfony\Component\HttpKernel\Exception\HttpException;
  22. use Symfony\Component\HttpKernel\Exception\NearMissValueResolverException;
  23. use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
  24. use Symfony\Component\HttpKernel\KernelEvents;
  25. use Symfony\Component\Serializer\Exception\NotEncodableValueException;
  26. use Symfony\Component\Serializer\Exception\PartialDenormalizationException;
  27. use Symfony\Component\Serializer\Exception\UnexpectedPropertyException;
  28. use Symfony\Component\Serializer\Exception\UnsupportedFormatException;
  29. use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
  30. use Symfony\Component\Serializer\SerializerInterface;
  31. use Symfony\Component\Validator\Constraints as Assert;
  32. use Symfony\Component\Validator\ConstraintViolation;
  33. use Symfony\Component\Validator\ConstraintViolationList;
  34. use Symfony\Component\Validator\Exception\ValidationFailedException;
  35. use Symfony\Component\Validator\Validator\ValidatorInterface;
  36. use Symfony\Contracts\Translation\TranslatorInterface;
  37. /**
  38. * @author Konstantin Myakshin <molodchick@gmail.com>
  39. *
  40. * @final
  41. */
  42. class RequestPayloadValueResolver implements ValueResolverInterface, EventSubscriberInterface
  43. {
  44. /**
  45. * @see DenormalizerInterface::COLLECT_DENORMALIZATION_ERRORS
  46. */
  47. private const CONTEXT_DENORMALIZE = [
  48. 'collect_denormalization_errors' => true,
  49. ];
  50. /**
  51. * @see DenormalizerInterface::COLLECT_DENORMALIZATION_ERRORS
  52. */
  53. private const CONTEXT_DESERIALIZE = [
  54. 'collect_denormalization_errors' => true,
  55. ];
  56. public function __construct(
  57. private readonly SerializerInterface&DenormalizerInterface $serializer,
  58. private readonly ?ValidatorInterface $validator = null,
  59. private readonly ?TranslatorInterface $translator = null,
  60. private string $translationDomain = 'validators',
  61. ) {
  62. }
  63. public function resolve(Request $request, ArgumentMetadata $argument): iterable
  64. {
  65. $attribute = $argument->getAttributesOfType(MapQueryString::class, ArgumentMetadata::IS_INSTANCEOF)[0]
  66. ?? $argument->getAttributesOfType(MapRequestPayload::class, ArgumentMetadata::IS_INSTANCEOF)[0]
  67. ?? $argument->getAttributesOfType(MapUploadedFile::class, ArgumentMetadata::IS_INSTANCEOF)[0]
  68. ?? null;
  69. if (!$attribute) {
  70. return [];
  71. }
  72. if (!$attribute instanceof MapUploadedFile && $argument->isVariadic()) {
  73. throw new \LogicException(\sprintf('Mapping variadic argument "$%s" is not supported.', $argument->getName()));
  74. }
  75. if ($attribute instanceof MapRequestPayload) {
  76. if ('array' === $argument->getType()) {
  77. if (!$attribute->type) {
  78. throw new NearMissValueResolverException(\sprintf('Please set the $type argument of the #[%s] attribute to the type of the objects in the expected array.', MapRequestPayload::class));
  79. }
  80. } elseif ($attribute->type) {
  81. throw new NearMissValueResolverException(\sprintf('Please set its type to "array" when using argument $type of #[%s].', MapRequestPayload::class));
  82. }
  83. }
  84. $attribute->metadata = $argument;
  85. return [$attribute];
  86. }
  87. public function onKernelControllerArguments(ControllerArgumentsEvent $event): void
  88. {
  89. $arguments = $event->getArguments();
  90. foreach ($arguments as $i => $argument) {
  91. if ($argument instanceof MapQueryString) {
  92. $payloadMapper = $this->mapQueryString(...);
  93. $validationFailedCode = $argument->validationFailedStatusCode;
  94. } elseif ($argument instanceof MapRequestPayload) {
  95. $payloadMapper = $this->mapRequestPayload(...);
  96. $validationFailedCode = $argument->validationFailedStatusCode;
  97. } elseif ($argument instanceof MapUploadedFile) {
  98. $payloadMapper = $this->mapUploadedFile(...);
  99. $validationFailedCode = $argument->validationFailedStatusCode;
  100. } else {
  101. continue;
  102. }
  103. $request = $event->getRequest();
  104. if (!$argument->metadata->getType()) {
  105. throw new \LogicException(\sprintf('Could not resolve the "$%s" controller argument: argument should be typed.', $argument->metadata->getName()));
  106. }
  107. if ($this->validator) {
  108. $violations = new ConstraintViolationList();
  109. try {
  110. $payload = $payloadMapper($request, $argument->metadata, $argument);
  111. } catch (PartialDenormalizationException $e) {
  112. $trans = $this->translator ? $this->translator->trans(...) : fn ($m, $p) => strtr($m, $p);
  113. foreach ($e->getErrors() as $error) {
  114. $parameters = [];
  115. $template = 'This value was of an unexpected type.';
  116. if ($expectedTypes = $error->getExpectedTypes()) {
  117. $template = 'This value should be of type {{ type }}.';
  118. $parameters['{{ type }}'] = implode('|', $expectedTypes);
  119. }
  120. if ($error->canUseMessageForUser()) {
  121. $parameters['hint'] = $error->getMessage();
  122. }
  123. $message = $trans($template, $parameters, $this->translationDomain);
  124. $violations->add(new ConstraintViolation($message, $template, $parameters, null, $error->getPath(), null));
  125. }
  126. $payload = $e->getData();
  127. }
  128. if (null !== $payload && !\count($violations)) {
  129. $constraints = $argument->constraints ?? null;
  130. if (\is_array($payload) && !empty($constraints) && !$constraints instanceof Assert\All) {
  131. $constraints = new Assert\All($constraints);
  132. }
  133. $violations->addAll($this->validator->validate($payload, $constraints, $argument->validationGroups ?? null));
  134. }
  135. if (\count($violations)) {
  136. throw HttpException::fromStatusCode($validationFailedCode, implode("\n", array_map(static fn ($e) => $e->getMessage(), iterator_to_array($violations))), new ValidationFailedException($payload, $violations));
  137. }
  138. } else {
  139. try {
  140. $payload = $payloadMapper($request, $argument->metadata, $argument);
  141. } catch (PartialDenormalizationException $e) {
  142. throw HttpException::fromStatusCode($validationFailedCode, implode("\n", array_map(static fn ($e) => $e->getMessage(), $e->getErrors())), $e);
  143. }
  144. }
  145. if (null === $payload) {
  146. $payload = match (true) {
  147. $argument->metadata->hasDefaultValue() => $argument->metadata->getDefaultValue(),
  148. $argument->metadata->isNullable() => null,
  149. default => throw HttpException::fromStatusCode($validationFailedCode),
  150. };
  151. }
  152. $arguments[$i] = $payload;
  153. }
  154. $event->setArguments($arguments);
  155. }
  156. public static function getSubscribedEvents(): array
  157. {
  158. return [
  159. KernelEvents::CONTROLLER_ARGUMENTS => 'onKernelControllerArguments',
  160. ];
  161. }
  162. private function mapQueryString(Request $request, ArgumentMetadata $argument, MapQueryString $attribute): ?object
  163. {
  164. if (!($data = $request->query->all()) && ($argument->isNullable() || $argument->hasDefaultValue())) {
  165. return null;
  166. }
  167. return $this->serializer->denormalize($data, $argument->getType(), 'csv', $attribute->serializationContext + self::CONTEXT_DENORMALIZE + ['filter_bool' => true]);
  168. }
  169. private function mapRequestPayload(Request $request, ArgumentMetadata $argument, MapRequestPayload $attribute): object|array|null
  170. {
  171. if (null === $format = $request->getContentTypeFormat()) {
  172. throw new UnsupportedMediaTypeHttpException('Unsupported format.');
  173. }
  174. if ($attribute->acceptFormat && !\in_array($format, (array) $attribute->acceptFormat, true)) {
  175. throw new UnsupportedMediaTypeHttpException(\sprintf('Unsupported format, expects "%s", but "%s" given.', implode('", "', (array) $attribute->acceptFormat), $format));
  176. }
  177. if ('array' === $argument->getType() && null !== $attribute->type) {
  178. $type = $attribute->type.'[]';
  179. } else {
  180. $type = $argument->getType();
  181. }
  182. if ($data = $request->request->all()) {
  183. return $this->serializer->denormalize($data, $type, 'csv', $attribute->serializationContext + self::CONTEXT_DENORMALIZE + ('form' === $format ? ['filter_bool' => true] : []));
  184. }
  185. if ('' === ($data = $request->getContent()) && ($argument->isNullable() || $argument->hasDefaultValue())) {
  186. return null;
  187. }
  188. if ('form' === $format) {
  189. throw new BadRequestHttpException('Request payload contains invalid "form" data.');
  190. }
  191. try {
  192. return $this->serializer->deserialize($data, $type, $format, self::CONTEXT_DESERIALIZE + $attribute->serializationContext);
  193. } catch (UnsupportedFormatException $e) {
  194. throw new UnsupportedMediaTypeHttpException(\sprintf('Unsupported format: "%s".', $format), $e);
  195. } catch (NotEncodableValueException $e) {
  196. throw new BadRequestHttpException(\sprintf('Request payload contains invalid "%s" data.', $format), $e);
  197. } catch (UnexpectedPropertyException $e) {
  198. throw new BadRequestHttpException(\sprintf('Request payload contains invalid "%s" property.', $e->property), $e);
  199. }
  200. }
  201. private function mapUploadedFile(Request $request, ArgumentMetadata $argument, MapUploadedFile $attribute): UploadedFile|array|null
  202. {
  203. return $request->files->get($attribute->name ?? $argument->getName(), []);
  204. }
  205. }