Skip to content

Commit

Permalink
feature #49978 [HttpKernel] Introduce #[MapUploadedFile] controller…
Browse files Browse the repository at this point in the history
… argument attribute (renedelima)

This PR was merged into the 7.1 branch.

Discussion
----------

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

| Q             | A
| ------------- | ---
| Branch?       | 7.1
| Bug fix?      | no
| New feature?  | yes
| Deprecations? | no
| Tickets       | #52678, #49138
| License       | MIT
| Doc PR        | -

## Usage Example

```php
# src/Controller/UserPictureController.php

namespace App\Controller;

use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\HttpKernel\Attribute\MapUploadedFile;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\Constraints as Assert;

#[AsController]
final class UserPictureController
{
    #[Route('/user/picture', methods: ['PUT'])]
    public function __invoke(
        #[MapUploadedFile(
            new Assert\File(mimeTypes: ['image/png', 'image/jpeg']),
        )] ?UploadedFile $picture,
    ): Response {
        return new Response('Your picture was updated');
    }
}
```

```php
# src/Controller/UserDocumentsController.php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\HttpKernel\Attribute\MapUploadedFile;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\Constraints as Assert;

final class UserDocumentsController
{
    #[Route('/user/documents', methods: ['PUT'])]
    public function __invoke(
        #[MapUploadedFile(
            new Assert\File(mimeTypes: ['application/pdf'])
        )] array $documents
    ): Response {
        return new Response('Thanks for sharing your documents');
    }
}
```

```php
# src/Controller/UserDocumentsController.php

namespace App\Controller;

use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\HttpKernel\Attribute\MapUploadedFile;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\Constraints as Assert;

final class UserDocumentsController
{
    #[Route('/user/documents', methods: ['PUT'])]
    public function __invoke(
        #[MapUploadedFile(
            new Assert\File(mimeTypes: ['application/pdf'])
        )] UploadedFile ...$documents
    ): Response {
        return new Response('Thanks for sharing your documents');
    }
}
```

Commits
-------

b85dbd0 [HttpKernel] Add MapUploadedFile attribute
  • Loading branch information
chalasr committed Apr 18, 2024
2 parents f02b0f2 + b85dbd0 commit 13ab9eb
Show file tree
Hide file tree
Showing 6 changed files with 408 additions and 11 deletions.
33 changes: 33 additions & 0 deletions src/Symfony/Component/HttpKernel/Attribute/MapUploadedFile.php
@@ -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 deletions src/Symfony/Component/HttpKernel/CHANGELOG.md
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
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 Down Expand 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(), []);
}
}

0 comments on commit 13ab9eb

Please sign in to comment.