New in Symfony 5.2: Uid serialization and validation
October 6, 2020 • Published by Javier Eguiluz
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
The Symfony Uid component provides tools to generate and work with unique identifiers such as UUIDs and ULIDs. In Symfony 5.2 we're improving its integration with the rest of the framework. In a previous article we showed the new Doctrine types for UUID and ULID and this article shows the integration with the Serializer and Validation components.
Uid normalizer
Contributed by
guillbdx
and Tomas Norkūnas
in #36406
and #38151.
Symfony 5.2 introduces a new UidNormalizer
class which can
normalize/denormalize properties with both UUID and ULID values.
Consider for example the following entity with a UUID property:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// src/Entity/Product.php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\ProductRepository")
*/
class Product
{
/**
* @ORM\Column(type="uuid")
*/
private $id;
// ...
}
Thanks to the new Uid normalizer (which is enabled by default, so you don't have to change anything in your application) this entity is automatically serialized and deserialized as expected:
1 2 3
$product = new Product();
$jsonContent = $serializer->serialize($product, 'json');
// $jsonContent contains {"id":"9b7541de-6f87-11ea-ab3c-9da9a81562fc","...":"..."}
Ulid validation
Contributed by
Laurent Clouet
in #38322.
Symfony has included a UUID validator since 2014 to validate UUID values of type 1 to 5.
Starting from Symfony 5.2, it will also include a Ulid
validation constraint to validate ULID values:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// src/Entity/Product.php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity(repositoryClass="App\Repository\ProductRepository")
*/
class Product
{
/**
* @ORM\Column(type="ulid")
* @Assert\Ulid
*/
private $someProperty;
// ...
}
A final improvement done by Nicolas Grekas in the Pull Request #38332 is the update of the existing UUID validator to also validate UUIDv6 values.
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.