RequestPayloadValueResolver.php 11 KB

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