Cover of the book Symfony 5: The Fast Track

Symfony 5: The Fast Track is the best book to learn modern Symfony development, from zero to production. +300 pages showcasing Symfony with Docker, APIs, queues & async tasks, Webpack, SPAs, etc.

New in Symfony 5.2: Uid serialization and validation

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.

New in Symfony 5.2: Uid serialization and validation symfony.com/blog/new-in-symfony-5-2-uid-serialization-and-validation

Tweet this

Comments

Thanks. Would be nice if we could configure how the normaliser normalised. Eg Rfc4122, Base32, Base58.
@Jordan would you mind sending a PR doing so? Or at least open an issue? Thanks!
Login with SymfonyConnect to post a comment