RequestPayloadValueResolver.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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\InvalidArgumentException as SerializerInvalidArgumentException;
  26. use Symfony\Component\Serializer\Exception\NotEncodableValueException;
  27. use Symfony\Component\Serializer\Exception\PartialDenormalizationException;
  28. use Symfony\Component\Serializer\Exception\UnexpectedPropertyException;
  29. use Symfony\Component\Serializer\Exception\UnsupportedFormatException;
  30. use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
  31. use Symfony\Component\Serializer\SerializerInterface;
  32. use Symfony\Component\Validator\Constraints as Assert;
  33. use Symfony\Component\Validator\ConstraintViolation;
  34. use Symfony\Component\Validator\ConstraintViolationList;
  35. use Symfony\Component\Validator\Exception\ValidationFailedException;
  36. use Symfony\Component\Validator\Validator\ValidatorInterface;
  37. use Symfony\Contracts\Translation\TranslatorInterface;
  38. /**
  39. * @author Konstantin Myakshin <molodchick@gmail.com>
  40. *
  41. * @final
  42. */
  43. class RequestPayloadValueResolver implements ValueResolverInterface, EventSubscriberInterface
  44. {
  45. /**
  46. * @see DenormalizerInterface::COLLECT_DENORMALIZATION_ERRORS
  47. */
  48. private const CONTEXT_DENORMALIZE = [
  49. 'collect_denormalization_errors' => true,
  50. ];
  51. /**
  52. * @see DenormalizerInterface::COLLECT_DENORMALIZATION_ERRORS
  53. */
  54. private const CONTEXT_DESERIALIZE = [
  55. 'collect_denormalization_errors' => true,
  56. ];
  57. public function __construct(
  58. private readonly SerializerInterface&DenormalizerInterface $serializer,
  59. private readonly ?ValidatorInterface $validator = null,
  60. private readonly ?TranslatorInterface $translator = null,
  61. private string $translationDomain = 'validators',
  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(...) : static 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, $this->translationDomain);
  125. $violations->add(new ConstraintViolation($message, $template, $parameters, null, $error->getPath(), null));
  126. }
  127. $payload = $e->getData();
  128. } catch (SerializerInvalidArgumentException $e) {
  129. $violations->add(new ConstraintViolation($e->getMessage(), $e->getMessage(), [], null, '', null));
  130. $payload = null;
  131. }
  132. if (null !== $payload && !\count($violations)) {
  133. $constraints = $argument->constraints ?? null;
  134. if (\is_array($payload) && !empty($constraints) && !$constraints instanceof Assert\All) {
  135. $constraints = new Assert\All($constraints);
  136. }
  137. if ($argument instanceof MapUploadedFile) {
  138. $violations->addAll($this->validator->startContext()->atPath($argument->metadata->getName())->validate($payload, $constraints, $argument->validationGroups ?? null)->getViolations());
  139. } else {
  140. $violations->addAll($this->validator->validate($payload, $constraints, $argument->validationGroups ?? null));
  141. }
  142. }
  143. if (\count($violations)) {
  144. throw HttpException::fromStatusCode($validationFailedCode, implode("\n", array_map(static fn ($e) => $e->getMessage(), iterator_to_array($violations))), new ValidationFailedException($payload, $violations));
  145. }
  146. } else {
  147. try {
  148. $payload = $payloadMapper($request, $argument->metadata, $argument);
  149. } catch (PartialDenormalizationException $e) {
  150. throw HttpException::fromStatusCode($validationFailedCode, implode("\n", array_map(static fn ($e) => $e->getMessage(), $e->getErrors())), $e);
  151. } catch (SerializerInvalidArgumentException $e) {
  152. throw HttpException::fromStatusCode($validationFailedCode, $e->getMessage(), $e);
  153. }
  154. }
  155. if ($argument->metadata->isVariadic()) {
  156. array_splice($arguments, $i, 1, $payload ?? []);
  157. continue;
  158. }
  159. if (null === $payload) {
  160. $payload = match (true) {
  161. $argument->metadata->hasDefaultValue() => $argument->metadata->getDefaultValue(),
  162. $argument->metadata->isNullable() => null,
  163. default => throw HttpException::fromStatusCode($validationFailedCode),
  164. };
  165. }
  166. $arguments[$i] = $payload;
  167. }
  168. $event->setArguments($arguments);
  169. }
  170. public static function getSubscribedEvents(): array
  171. {
  172. return [
  173. KernelEvents::CONTROLLER_ARGUMENTS => 'onKernelControllerArguments',
  174. ];
  175. }
  176. private function mapQueryString(Request $request, ArgumentMetadata $argument, MapQueryString $attribute): ?object
  177. {
  178. if (!($data = $request->query->all($attribute->key)) && ($argument->isNullable() || $argument->hasDefaultValue())) {
  179. return null;
  180. }
  181. return $this->serializer->denormalize($data, $argument->getType(), 'csv', $attribute->serializationContext + self::CONTEXT_DENORMALIZE + ['filter_bool' => true]);
  182. }
  183. private function mapRequestPayload(Request $request, ArgumentMetadata $argument, MapRequestPayload $attribute): object|array|null
  184. {
  185. if ('' === ($data = $request->request->all() ?: $request->getContent()) && ($argument->isNullable() || $argument->hasDefaultValue())) {
  186. return null;
  187. }
  188. if (null === $format = $request->getContentTypeFormat()) {
  189. throw new UnsupportedMediaTypeHttpException('Unsupported format.');
  190. }
  191. if ($attribute->acceptFormat && !\in_array($format, (array) $attribute->acceptFormat, true)) {
  192. throw new UnsupportedMediaTypeHttpException(\sprintf('Unsupported format, expects "%s", but "%s" given.', implode('", "', (array) $attribute->acceptFormat), $format));
  193. }
  194. if ('array' === $argument->getType() && null !== $attribute->type) {
  195. $type = $attribute->type.'[]';
  196. } else {
  197. $type = $argument->getType();
  198. }
  199. if (\is_array($data)) {
  200. return $this->serializer->denormalize($data, $type, self::hasNonStringScalar($data) ? $format : 'csv', $attribute->serializationContext + self::CONTEXT_DENORMALIZE + ('form' === $format ? ['filter_bool' => true] : []));
  201. }
  202. if ('form' === $format) {
  203. throw new BadRequestHttpException('Request payload contains invalid "form" data.');
  204. }
  205. try {
  206. return $this->serializer->deserialize($data, $type, $format, self::CONTEXT_DESERIALIZE + $attribute->serializationContext);
  207. } catch (UnsupportedFormatException $e) {
  208. throw new UnsupportedMediaTypeHttpException(\sprintf('Unsupported format: "%s".', $format), $e);
  209. } catch (NotEncodableValueException $e) {
  210. throw new BadRequestHttpException(\sprintf('Request payload contains invalid "%s" data.', $format), $e);
  211. } catch (UnexpectedPropertyException $e) {
  212. throw new BadRequestHttpException(\sprintf('Request payload contains invalid "%s" property.', $e->property), $e);
  213. }
  214. }
  215. private function mapUploadedFile(Request $request, ArgumentMetadata $argument, MapUploadedFile $attribute): UploadedFile|array|null
  216. {
  217. if ($files = $request->files->get($attribute->name ?? $argument->getName())) {
  218. return !\is_array($files) && $argument->isVariadic() ? [$files] : $files;
  219. }
  220. if ($argument->isNullable() || $argument->hasDefaultValue()) {
  221. return null;
  222. }
  223. return 'array' === $argument->getType() ? [] : null;
  224. }
  225. private static function hasNonStringScalar(array $data): bool
  226. {
  227. $stack = [$data];
  228. while ($stack) {
  229. foreach (array_pop($stack) as $v) {
  230. if (\is_array($v)) {
  231. $stack[] = $v;
  232. } elseif (!\is_string($v)) {
  233. return true;
  234. }
  235. }
  236. }
  237. return false;
  238. }
  239. }