Symfony can inject services, map request data into typed objects and fetch Doctrine entities based on the arguments of your controllers. Symfony 8.2 improves this feature to make it work in more cases, and some improvements apply to console commands too.

Union and Intersection Types

HypeMC
Contributed by HypeMC in #65368

Union and intersection types tell exactly what you need from a service (e.g. something that both normalizes and denormalizes). Autowiring supported them in constructors, but controller actions and invokable commands rejected them with a "non-existent class or interface" error. In Symfony 8.2, they work the same everywhere:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class ProductController
{
    #[Route('/products/{id}/duplicate', methods: ['POST'])]
    public function duplicate(
        Product $product,
        NormalizerInterface&DenormalizerInterface $serializer,
    ): Response {
        // ...
    }
}

#[AsCommand('app:products:import')]
class ImportProductsCommand
{
    public function __invoke(NormalizerInterface&DenormalizerInterface $serializer): int
    {
        // ...
    }
}

The rules are the same as in constructors: the type is autowired when all its members are aliases of the same service, in intersections (A&B) and unions (A|B). Built-in types are ignored (A|string resolves as A), nullable types and #[Target] are supported, and types that mix both ((A&B)|C) need #[Autowire(service: '...')].

More Types in #[MapQueryParameter] and #[MapRequestHeader]

Nicolas Grekas
Contributed by Nicolas Grekas in #65386

Symfony 8.2 improves the #[MapQueryParameter] and #[MapRequestHeader] attributes to accept any type that another resolver can build, such as dates and Doctrine entities:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
use Symfony\Component\HttpKernel\Attribute\MapDateTime;
use Symfony\Component\HttpKernel\Attribute\MapQueryParameter;
use Symfony\Component\HttpKernel\Attribute\MapRequestHeader;
use Symfony\Component\Uid\Ulid;

// GET /invoices?customer=37&from=2026-01-15&to=31/01/2026
#[Route('/invoices')]
public function list(
    #[MapQueryParameter] Customer $customer,
    #[MapQueryParameter] \DateTimeImmutable $from,
    #[MapQueryParameter] #[MapDateTime(format: 'd/m/Y')] \DateTimeImmutable $to,
    #[MapRequestHeader('x-request-id')] Ulid $requestId,
): Response {
    // ...
}

When these attributes read a value they can't convert, they store it in the request attributes (under the name of the argument) and let the next resolvers handle it, as if it came from the route. Resolvers that work like this implement the new SourceValueResolverInterface, which you can use in your own resolvers too.

Authorization Checks on Mapped Payloads

Nicolas Grekas
Contributed by Nicolas Grekas in #66634

The #[IsGranted] attribute runs before #[MapRequestPayload], #[MapQueryString] and #[MapUploadedFile] map their arguments, so unauthorized users can't make your application parse their payloads. The downside is that voters couldn't vote on the mapped object, because it didn't exist yet.

In Symfony 8.2, when the subject of #[IsGranted] reads one of those arguments, Symfony maps and validates it first and then calls the voters:

1
2
3
4
5
6
7
8
9
10
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[Route('/posts', methods: ['POST'])]
#[IsGranted('IS_AUTHENTICATED')]    // runs before the payload is parsed
#[IsGranted('POST_CREATE', 'post')] // maps $post, then votes on it
public function create(#[MapRequestPayload] PostDto $post): Response
{
    // ...
}

Attributes are checked in order, so earlier checks still run without parsing the payload. Since the payload is validated before voting, invalid payloads get a validation error instead of an access denied error. This is a backward compatibility break for voters that received the mapping attribute as their subject: they now receive the mapped object.

Lists of Entities in #[MapEntity]

Adrian Brajković
Contributed by Adrian Brajković in #63949

The #[MapEntity] attribute always looked for a single entity, so getting a list required a repository.findBy(...) expression. In Symfony 8.2, when the argument type is array, the attribute uses findBy() instead of findOneBy() with the same mapping options:

1
2
3
4
5
6
7
8
9
use Symfony\Bridge\Doctrine\Attribute\MapEntity;

#[Route('/authors/{authorId}/posts')]
public function authorPosts(
    #[MapEntity(class: Post::class, mapping: ['authorId' => 'author'])]
    array $posts,
): Response {
    // ...
}

If no entities are found, you get an empty array instead of a 404 error. This also works in the array arguments of console commands. To sort or limit the results, keep using expr.

Closures in #[MapEntity]

HypeMC
Contributed by HypeMC in #63866

The expr option of #[MapEntity] fetches entities with an expression that calls any method of the repository. Expressions are strings, so your IDE and static analysis tools can't help with them. In Symfony 8.2, this option also accepts a closure, which receives the request and the entity repository (closures in attributes require PHP 8.5):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
use App\Repository\PostRepository;
use Symfony\Bridge\Doctrine\Attribute\MapEntity;
use Symfony\Component\HttpFoundation\Request;

#[Route('/authors/{authorId}/posts/latest')]
public function latestPosts(
    #[MapEntity(
        class: Post::class,
        expr: static function (Request $request, PostRepository $repository): array {
            return $repository->findBy(
                ['author' => $request->attributes->get('authorId')],
                ['publishedAt' => 'DESC'],
                10,
            );
        },
    )]
    array $posts,
): Response {
    // ...
}

In console commands, the closure receives the command input instead of the request.

JSON Query Parameters in #[MapQueryString]

Mudassar Ali
Contributed by Mudassar Ali in #64368

The key option of #[MapQueryString] maps a single query parameter into an object instead of the whole query string. That parameter had to use the array notation (?search[term]=...), but some API clients prefer to send complex filters as JSON. In Symfony 8.2, when the parameter contains a string, it's deserialized as JSON:

1
2
3
4
5
6
7
8
9
10
use Symfony\Component\HttpKernel\Attribute\MapQueryString;

// both URLs now create the same object:
// /products?search[term]=keyboard&search[category]=accessories
// /products?search={"term":"keyboard","category":"accessories"}
#[Route('/products')]
public function list(#[MapQueryString(key: 'search')] SearchDto $search): Response
{
    // ...
}

The other options (validation groups, serialization context, etc.) work as before and malformed JSON returns a 400 error. Nothing changes when you don't set the key option.

Structured Media Types in #[MapRequestPayload]

Pascal CESCON
Contributed by Pascal CESCON in #63804

Many APIs use media types such as application/vnd.api+json or application/ld+json. Their content is plain JSON, but Symfony associates them with their own formats (jsonapi, jsonld). Unless you had an encoder for those formats, #[MapRequestPayload] rejected these requests with a 415 error.

In Symfony 8.2, when the serializer can't decode the request format, #[MapRequestPayload] falls back to the format of the suffix of the media type (+json or +xml):

1
2
3
4
5
6
7
8
9
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;

// this controller now also accepts requests sent with content types like:
//   application/vnd.api+json, application/ld+json, application/problem+json
#[Route('/articles', methods: ['POST'])]
public function create(#[MapRequestPayload] ArticleDto $article): Response
{
    // ...
}

If your application defines encoders for those formats (as API Platform does), they are still used. The new Request::getStructuredSuffixFormat() method provides the same logic to your own code:

1
2
3
use Symfony\Component\HttpFoundation\Request;

Request::getStructuredSuffixFormat('application/hal+xml'); // 'xml'
Published in #Living on the edge