Symfony 8.2 New Published on

A generic page of results, Page<Produit>

Symfony 8.2's Serializer understands PHPDoc generics: a single Page class, holding Produit or Avis objects depending on the property that carries it.

Topics covered: SerializerAPI

New in Symfony 8.2 (in development). An API often returns its lists in pages: items, a total, sometimes a link to the next one. The same envelope, around products, reviews or orders. In PHP, you describe it once, with a PHPDoc generic:

/** @template T */
class Page
{
    /** @var list<T> */
    public array $items = [];
    public int $total = 0;
}

Until now, the Serializer didn't know what to do with T: it deserialized it as its bound, or as a plain array. You ended up writing a ProductsPage, a ReviewsPage…

Since Symfony 8.2

The Serializer resolves the type parameters from the generic declared on the property that carries the object:

class Catalogue
{
    /** @var Page<Produit> */
    public Page $products;
}

$catalogue = $serializer->deserialize($json, Catalogue::class, 'json');
// $catalogue->products->items[0] is a Produit

It also works with nested or nullable generics, several parameters, constructor arguments and collections such as list<Page<Produit>>. It needs PropertyInfo's PhpStanExtractor, and therefore the phpstan/phpdoc-parser and phpdocumentor/type-resolver packages.

The Serializer also becomes stricter: a list<string> must receive a JSON array, and an object {"5": "a", "1": "b"} triggers a deprecation there, which will become an exception in 9.0.

Your task

ClientFournisseur deserializes the response of a supplier's API (the reponse.json file) into a Catalogue: a page of products, a page of reviews. But Page only holds arrays, and /catalogue crashes.

  1. Make Page a generic page, and say what it holds in each property of Catalogue.

Where the feature comes from: the original pull request.