Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[HttpKernel] Introduce#[MapUploadedFile] controller argument attribute#49978

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
chalasr merged 1 commit intosymfony:7.1fromrenedelima:map-uploaded-file
Apr 18, 2024
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\HttpKernel\Attribute;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\RequestPayloadValueResolver;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
use Symfony\Component\Validator\Constraint;

#[\Attribute(\Attribute::TARGET_PARAMETER)]
class MapUploadedFile extends ValueResolver
{
public ArgumentMetadata $metadata;

public function __construct(
/** @var Constraint|array<Constraint>|null */
public Constraint|array|null $constraints = null,
public ?string $name = null,
string $resolver = RequestPayloadValueResolver::class,
public readonly int $validationFailedStatusCode = Response::HTTP_UNPROCESSABLE_ENTITY,
) {
parent::__construct($resolver);
}
}
1 change: 1 addition & 0 deletionssrc/Symfony/Component/HttpKernel/CHANGELOG.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,6 +10,7 @@ CHANGELOG
* Add `NearMissValueResolverException` to let value resolvers report when an argument could be under their watch but failed to be resolved
* Add `$type` argument to `#[MapRequestPayload]` that allows mapping a list of items
* Deprecate `Extension::addAnnotatedClassesToCompile()` and related code infrastructure
* Add `#[MapUploadedFile]` attribute to fetch, validate, and inject uploaded files into controller arguments

7.0
---
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,9 +12,11 @@
namespace Symfony\Component\HttpKernel\Controller\ArgumentResolver;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Attribute\MapQueryString;
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
use Symfony\Component\HttpKernel\Attribute\MapUploadedFile;
use Symfony\Component\HttpKernel\Controller\ValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
Expand All@@ -29,6 +31,7 @@
use Symfony\Component\Serializer\Exception\UnsupportedFormatException;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\Exception\ValidationFailedException;
Expand DownExpand Up@@ -69,13 +72,14 @@ 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 ($argument->isVariadic()) {
if (!$attribute instanceof MapUploadedFile &&$argument->isVariadic()) {
throw new \LogicException(sprintf('Mapping variadic argument "$%s" is not supported.', $argument->getName()));
}

Expand All@@ -100,24 +104,27 @@ public function onKernelControllerArguments(ControllerArgumentsEvent $event): vo

foreach ($arguments as $i => $argument) {
if ($argument instanceof MapQueryString) {
$payloadMapper ='mapQueryString';
$payloadMapper =$this->mapQueryString(...);
$validationFailedCode = $argument->validationFailedStatusCode;
} elseif ($argument instanceof MapRequestPayload) {
$payloadMapper = 'mapRequestPayload';
$payloadMapper = $this->mapRequestPayload(...);
$validationFailedCode = $argument->validationFailedStatusCode;
} elseif ($argument instanceof MapUploadedFile) {
$payloadMapper = $this->mapUploadedFile(...);
$validationFailedCode = $argument->validationFailedStatusCode;
} else {
continue;
}
$request = $event->getRequest();

if (!$type = $argument->metadata->getType()) {
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 = $this->$payloadMapper($request, $type, $argument);
$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) {
Expand All@@ -137,15 +144,19 @@ public function onKernelControllerArguments(ControllerArgumentsEvent $event): vo
}

if (null !== $payload && !\count($violations)) {
$violations->addAll($this->validator->validate($payload, null, $argument->validationGroups ?? null));
$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 = $this->$payloadMapper($request, $type, $argument);
$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);
}
Expand All@@ -172,16 +183,16 @@ public static function getSubscribedEvents(): array
];
}

private function mapQueryString(Request $request,string $type, MapQueryString $attribute): ?object
private function mapQueryString(Request $request,ArgumentMetadata $argument, MapQueryString $attribute): ?object
{
if (!$data = $request->query->all()) {
return null;
}

return $this->serializer->denormalize($data, $type, null, $attribute->serializationContext + self::CONTEXT_DENORMALIZE + ['filter_bool' => true]);
return $this->serializer->denormalize($data, $argument->getType(), null, $attribute->serializationContext + self::CONTEXT_DENORMALIZE + ['filter_bool' => true]);
}

private function mapRequestPayload(Request $request,string $type, MapRequestPayload $attribute): object|array|null
private function mapRequestPayload(Request $request,ArgumentMetadata $argument, MapRequestPayload $attribute): object|array|null
{
if (null === $format = $request->getContentTypeFormat()) {
throw new UnsupportedMediaTypeHttpException('Unsupported format.');
Expand All@@ -191,8 +202,10 @@ private function mapRequestPayload(Request $request, string $type, MapRequestPay
throw new UnsupportedMediaTypeHttpException(sprintf('Unsupported format, expects "%s", but "%s" given.', implode('", "', (array) $attribute->acceptFormat), $format));
}

if ('array' === $type && null !== $attribute->type) {
if ('array' === $argument->getType() && null !== $attribute->type) {
$type = $attribute->type.'[]';
} else {
$type = $argument->getType();
}

if ($data = $request->request->all()) {
Expand All@@ -217,4 +230,9 @@ private function mapRequestPayload(Request $request, string $type, MapRequestPay
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(), []);
}
}
Loading

[8]ページ先頭

©2009-2025 Movatter.jp