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
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
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.
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!