The Serializer component turns objects into formats like JSON, XML or CSV and back. Symfony 8.2 makes its discriminator maps more flexible, makes denormalization more tolerant of invalid input and lets it understand more of the types that your classes inherit.
Extending Discriminator Maps from Child Classes
The #[DiscriminatorMap] attribute lists all the classes that a parent class
or interface can be denormalized into. That list lives in the parent, so adding
a new child class means editing the parent too, which is not possible when
the parent belongs to a bundle or a shared package.
Symfony 8.2 adds a #[DiscriminatorMapType] attribute that lets each class
add itself to the map declared by one of its parents or interfaces. The
mapping argument of #[DiscriminatorMap] is now optional:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
namespace App\Notification;
use Symfony\Component\Serializer\Attribute\DiscriminatorMap;
use Symfony\Component\Serializer\Attribute\DiscriminatorMapType;
#[DiscriminatorMap(typeProperty: 'channel')]
abstract class Notification
{
// ...
}
#[DiscriminatorMapType('sms', class: Notification::class)]
final class SmsNotification extends Notification
{
// ...
}
The attribute is repeatable, so a class can register several type names. Types
added this way are merged with the ones listed in mapping, and they also
extend maps declared in YAML or XML files. Duplicate type names and classes
that don't extend the parent are reported when building the container.
Type Aliases Survive a Round Trip
A discriminator map can point several type names to the same class, which is handy to keep a legacy name working. Denormalization handled those aliases fine, but normalization always wrote the first type name that matched the class, so the original name was lost:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
use Symfony\Component\Serializer\Attribute\DiscriminatorMap;
#[DiscriminatorMap(typeProperty: 'type', mapping: [
'invoice' => Invoice::class,
'bill' => Invoice::class, // legacy name of the same class
'receipt' => Receipt::class,
])]
abstract class Document
{
public function __construct(
public string $type,
public string $number,
) {
}
}
$json = '{"type":"bill","number":"2026-0042"}';
$document = $serializer->deserialize($json, Document::class, 'json');
$serializer->serialize($document, 'json');
// Before: {"type":"invoice","number":"2026-0042"}
// Symfony 8.2: {"type":"bill","number":"2026-0042"}
In Symfony 8.2, when several types map to the class of the object, the Serializer reads the discriminator property of the object to pick the right one. The property can hold a string, an integer or a backed enum. If it's unset or holds a value that doesn't map to that class, the first declared type is used, as before.
Skipping Invalid Attributes
Denormalizing user input is all or nothing: a single value of the wrong type
makes the whole operation fail, even when the class declares a good default
for it. That's why a controller using #[MapQueryString] returns a 404 error
when someone changes ?page=2 to ?page=foo in the URL.
Symfony 8.2 adds a skip_invalid_attributes option that handles those
values as if they were not in the input:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
class SearchQuery
{
public function __construct(
public int $page = 1,
public string $sort = 'date',
) {
}
}
$query = $serializer->denormalize(['page' => 'foo', 'sort' => 'price'], SearchQuery::class, null, [
AbstractNormalizer::SKIP_INVALID_ATTRIBUTES => true,
]);
// $query->page is 1 and $query->sort is 'price'
You can enable it in any serialization context, for example when mapping the query string in a controller:
1 2 3 4 5 6 7 8 9
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\MapQueryString;
public function search(
#[MapQueryString(serializationContext: ['skip_invalid_attributes' => true])]
SearchQuery $query,
): Response {
// /search?page=foo no longer returns a 404 error; $query->page is 1
}
An invalid value follows the same path as a missing one, so a required
constructor argument without a default value still fails. Skipped values are
not reported when you also use the collect_denormalization_errors option.
Mapping and Reordering CSV Columns
The csv_headers option of the CSV encoder sets the order of the columns,
but the column names are always the keys of the data and any column that you
don't list is added at the end. That's rarely what you want when the CSV file
is an export for other people.
In Symfony 8.2, this option also accepts an associative array that maps each column label to the value it contains:
1 2 3 4 5 6 7 8 9 10 11 12 13
use Symfony\Component\Serializer\Encoder\CsvEncoder;
$customers = [
['name' => 'Jane Doe', 'address' => ['city' => 'Lyon', 'zip' => '69001'], 'notes' => '...'],
['name' => 'John Smith', 'address' => ['city' => 'Leeds', 'zip' => 'LS1'], 'notes' => '...'],
];
$csv = $serializer->encode($customers, 'csv', [
CsvEncoder::HEADERS_KEY => ['City' => 'address.city', 'Customer' => 'name'],
]);
// City,Customer
// Lyon,"Jane Doe"
// Leeds,"John Smith"
Only the listed columns are included, in the given order. Nested values use the
same separator as flattened column names (. by default) and a missing value
results in an empty cell. This only applies when encoding; a list of names
keeps working as before.
Templates Inherited from Parent Classes
Symfony 8.2 teaches the Serializer to denormalize generic types declared on
the property that holds the object. However, many generic classes are used
through child classes that set the template with an @extends tag.
The TypeInfo component also resolves the templates that a class passes to its
parent classes, interfaces and traits with the @extends, @implements
and @use tags:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/**
* @template T
*/
class ApiResponse
{
/** @var T */
public mixed $data = null;
}
/**
* @extends ApiResponse<Product>
*/
class ProductResponse extends ApiResponse
{
}
$response = $serializer->deserialize('{"data":{"name":"Keyboard"}}', ProductResponse::class, 'json');
// $response->data is a Product
This also fixes child classes that rename or reorder the templates of their
parent (e.g. @extends ApiResponse<U>), and the PropertyInfo component
returns the same types. As with the rest of the generics support, this requires
the PhpStanExtractor and the phpstan/phpdoc-parser package.
PHPDoc Types Inherited from Parent Classes
When a class redeclares a property of its parent, for example to add an attribute to it, you usually don't copy the PHPDoc of the parent. Symfony then only saw the native type of the property, which says much less:
1 2 3 4 5 6 7 8 9 10 11 12 13
use Symfony\Component\Serializer\Attribute\Groups;
abstract class AbstractOrder
{
/** @var list<OrderLine> */
public array $lines = [];
}
class Order extends AbstractOrder
{
#[Groups(['read'])]
public array $lines = [];
}
In Symfony 8.2, the PropertyInfo and TypeInfo components inherit the PHPDoc
type of the parent member, like static analyzers do, so the type of
Order::$lines is list<OrderLine>. This works for properties, getters,
setters and constructor arguments, and for types declared in parent classes,
interfaces and abstract methods of traits. The type is only inherited when both
members have the same native type or when the parent has none.
This changes how the Serializer handles those properties: Order::$lines is
now denormalized as OrderLine objects instead of arrays. To keep the previous
behavior, add a PHPDoc type to the child property (e.g. @var array<mixed>).