class RequestPayloadValueResolver
@author Konstantin Myakshin <molodchick@gmail.com>
@final
Hierarchy
- class \Symfony\Component\HttpKernel\Controller\ArgumentResolver\RequestPayloadValueResolver implements \Symfony\Component\HttpKernel\Controller\ValueResolverInterface, \Symfony\Component\EventDispatcher\EventSubscriberInterface
Expanded class hierarchy of RequestPayloadValueResolver
3 files declare their use of RequestPayloadValueResolver
- MapQueryString.php in vendor/
symfony/ http-kernel/ Attribute/ MapQueryString.php - MapRequestPayload.php in vendor/
symfony/ http-kernel/ Attribute/ MapRequestPayload.php - MapUploadedFile.php in vendor/
symfony/ http-kernel/ Attribute/ MapUploadedFile.php
File
-
vendor/
symfony/ http-kernel/ Controller/ ArgumentResolver/ RequestPayloadValueResolver.php, line 46
Namespace
Symfony\Component\HttpKernel\Controller\ArgumentResolverView source
class RequestPayloadValueResolver implements ValueResolverInterface, EventSubscriberInterface {
/**
* @see \Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer::DISABLE_TYPE_ENFORCEMENT
* @see DenormalizerInterface::COLLECT_DENORMALIZATION_ERRORS
*/
private const CONTEXT_DENORMALIZE = [
'disable_type_enforcement' => true,
'collect_denormalization_errors' => true,
];
/**
* @see DenormalizerInterface::COLLECT_DENORMALIZATION_ERRORS
*/
private const CONTEXT_DESERIALIZE = [
'collect_denormalization_errors' => true,
];
public function __construct(SerializerInterface&DenormalizerInterface $serializer, ?ValidatorInterface $validator = null, ?TranslatorInterface $translator = null, string $translationDomain = 'validators') {
}
public function resolve(Request $request, ArgumentMetadata $argument) : iterable {
$attribute = $argument->getAttributesOfType(MapQueryString::class, ArgumentMetadata::IS_INSTANCEOF)[0] ?? $argument->getAttributesOfType(MapRequestPayload::class, ArgumentMetadata::IS_INSTANCEOF)[0] ?? $argument->getAttributesOfType(MapUploadedFile::class, ArgumentMetadata::IS_INSTANCEOF)[0] ?? null;
if (!$attribute) {
return [];
}
if (!$attribute instanceof MapUploadedFile && $argument->isVariadic()) {
throw new \LogicException(\sprintf('Mapping variadic argument "$%s" is not supported.', $argument->getName()));
}
if ($attribute instanceof MapRequestPayload) {
if ('array' === $argument->getType()) {
if (!$attribute->type) {
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));
}
}
elseif ($attribute->type) {
throw new NearMissValueResolverException(\sprintf('Please set its type to "array" when using argument $type of #[%s].', MapRequestPayload::class));
}
}
$attribute->metadata = $argument;
return [
$attribute,
];
}
public function onKernelControllerArguments(ControllerArgumentsEvent $event) : void {
$arguments = $event->getArguments();
foreach ($arguments as $i => $argument) {
if ($argument instanceof MapQueryString) {
$payloadMapper = $this->mapQueryString(...);
$validationFailedCode = $argument->validationFailedStatusCode;
}
elseif ($argument instanceof MapRequestPayload) {
$payloadMapper = $this->mapRequestPayload(...);
$validationFailedCode = $argument->validationFailedStatusCode;
}
elseif ($argument instanceof MapUploadedFile) {
$payloadMapper = $this->mapUploadedFile(...);
$validationFailedCode = $argument->validationFailedStatusCode;
}
else {
continue;
}
$request = $event->getRequest();
if (!$argument->metadata
->getType()) {
throw new \LogicException(\sprintf('Could not resolve the "$%s" controller argument: argument should be typed.', $argument->metadata
->getName()));
}
if ($this->validator) {
$violations = new ConstraintViolationList();
try {
$payload = $payloadMapper($request, $argument->metadata, $argument);
} catch (PartialDenormalizationException $e) {
$trans = $this->translator ? $this->translator
->trans(...) : fn($m, $p) => strtr($m, $p);
foreach ($e->getErrors() as $error) {
$parameters = [];
$template = 'This value was of an unexpected type.';
if ($expectedTypes = $error->getExpectedTypes()) {
$template = 'This value should be of type {{ type }}.';
$parameters['{{ type }}'] = implode('|', $expectedTypes);
}
if ($error->canUseMessageForUser()) {
$parameters['hint'] = $error->getMessage();
}
$message = $trans($template, $parameters, $this->translationDomain);
$violations->add(new ConstraintViolation($message, $template, $parameters, null, $error->getPath(), null));
}
$payload = $e->getData();
}
if (null !== $payload && !\count($violations)) {
$constraints = $argument->constraints ?? null;
if (\is_array($payload) && !empty($constraints) && !$constraints instanceof Assert\All) {
$constraints = new Assert\All($constraints);
}
$violations->addAll($this->validator
->validate($payload, $constraints, $argument->validationGroups ?? null));
}
if (\count($violations)) {
throw HttpException::fromStatusCode($validationFailedCode, implode("\n", array_map(static fn($e) => $e->getMessage(), iterator_to_array($violations))), new ValidationFailedException($payload, $violations));
}
}
else {
try {
$payload = $payloadMapper($request, $argument->metadata, $argument);
} catch (PartialDenormalizationException $e) {
throw HttpException::fromStatusCode($validationFailedCode, implode("\n", array_map(static fn($e) => $e->getMessage(), $e->getErrors())), $e);
}
}
if (null === $payload) {
$payload = match (true) { $argument->metadata
->hasDefaultValue() => $argument->metadata
->getDefaultValue(),
$argument->metadata
->isNullable() => null,
default => throw HttpException::fromStatusCode($validationFailedCode),
};
}
$arguments[$i] = $payload;
}
$event->setArguments($arguments);
}
public static function getSubscribedEvents() : array {
return [
KernelEvents::CONTROLLER_ARGUMENTS => 'onKernelControllerArguments',
];
}
private function mapQueryString(Request $request, ArgumentMetadata $argument, MapQueryString $attribute) : ?object {
if (!($data = $request->query
->all()) && ($argument->isNullable() || $argument->hasDefaultValue())) {
return null;
}
return $this->serializer
->denormalize($data, $argument->getType(), null, $attribute->serializationContext + self::CONTEXT_DENORMALIZE + [
'filter_bool' => true,
]);
}
private function mapRequestPayload(Request $request, ArgumentMetadata $argument, MapRequestPayload $attribute) : object|array|null {
if (null === ($format = $request->getContentTypeFormat())) {
throw new UnsupportedMediaTypeHttpException('Unsupported format.');
}
if ($attribute->acceptFormat && !\in_array($format, (array) $attribute->acceptFormat, true)) {
throw new UnsupportedMediaTypeHttpException(\sprintf('Unsupported format, expects "%s", but "%s" given.', implode('", "', (array) $attribute->acceptFormat), $format));
}
if ('array' === $argument->getType() && null !== $attribute->type) {
$type = $attribute->type . '[]';
}
else {
$type = $argument->getType();
}
if ($data = $request->request
->all()) {
return $this->serializer
->denormalize($data, $type, null, $attribute->serializationContext + self::CONTEXT_DENORMALIZE + ('form' === $format ? [
'filter_bool' => true,
] : []));
}
if ('' === ($data = $request->getContent()) && ($argument->isNullable() || $argument->hasDefaultValue())) {
return null;
}
if ('form' === $format) {
throw new BadRequestHttpException('Request payload contains invalid "form" data.');
}
try {
return $this->serializer
->deserialize($data, $type, $format, self::CONTEXT_DESERIALIZE + $attribute->serializationContext);
} catch (UnsupportedFormatException $e) {
throw new UnsupportedMediaTypeHttpException(\sprintf('Unsupported format: "%s".', $format), $e);
} catch (NotEncodableValueException $e) {
throw new BadRequestHttpException(\sprintf('Request payload contains invalid "%s" data.', $format), $e);
} catch (UnexpectedPropertyException $e) {
throw new BadRequestHttpException(\sprintf('Request payload contains invalid "%s" property.', $e->property), $e);
}
}
private function mapUploadedFile(Request $request, ArgumentMetadata $argument, MapUploadedFile $attribute) : UploadedFile|array|null {
return $request->files
->get($attribute->name ?? $argument->getName(), []);
}
}
Members
Title Sort descending | Modifiers | Object type | Summary | Overriden Title |
---|---|---|---|---|
RequestPayloadValueResolver::CONTEXT_DENORMALIZE | private | constant | ||
RequestPayloadValueResolver::CONTEXT_DESERIALIZE | private | constant | ||
RequestPayloadValueResolver::getSubscribedEvents | public static | function | Returns an array of event names this subscriber wants to listen to. | Overrides EventSubscriberInterface::getSubscribedEvents |
RequestPayloadValueResolver::mapQueryString | private | function | ||
RequestPayloadValueResolver::mapRequestPayload | private | function | ||
RequestPayloadValueResolver::mapUploadedFile | private | function | ||
RequestPayloadValueResolver::onKernelControllerArguments | public | function | ||
RequestPayloadValueResolver::resolve | public | function | Returns the possible value(s). | Overrides ValueResolverInterface::resolve |
RequestPayloadValueResolver::__construct | public | function |