Skip to content

[Uid] Add UidFactory to create Ulid and Uuid from timestamps and randomness/nodes #39507

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 11, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Symfony/Bridge/Doctrine/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ CHANGELOG

* Deprecate `DoctrineTestHelper` and `TestRepositoryFactory`
* [BC BREAK] Remove `UuidV*Generator` classes
* Add `UuidGenerator`

5.2.0
-----
Expand Down
12 changes: 12 additions & 0 deletions src/Symfony/Bridge/Doctrine/IdGenerator/UlidGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,24 @@

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Id\AbstractIdGenerator;
use Symfony\Component\Uid\Factory\UlidFactory;
use Symfony\Component\Uid\Ulid;

final class UlidGenerator extends AbstractIdGenerator
{
private $factory;

public function __construct(UlidFactory $factory = null)
{
$this->factory = $factory;
}

public function generate(EntityManager $em, $entity): Ulid
{
if ($this->factory) {
return $this->factory->create();
}

return new Ulid();
}
}
82 changes: 82 additions & 0 deletions src/Symfony/Bridge/Doctrine/IdGenerator/UuidGenerator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bridge\Doctrine\IdGenerator;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Id\AbstractIdGenerator;
use Symfony\Component\Uid\Factory\UuidFactory;
use Symfony\Component\Uid\Uuid;

final class UuidGenerator extends AbstractIdGenerator
{
private $protoFactory;
private $factory;
private $entityGetter;

public function __construct(UuidFactory $factory = null)
{
$this->protoFactory = $this->factory = $factory ?? new UuidFactory();
}

public function generate(EntityManager $em, $entity): Uuid
{
if (null !== $this->entityGetter) {
if (\is_callable([$entity, $this->entityGetter])) {
return $this->factory->create($entity->{$this->entityGetter}());
}

return $this->factory->create($entity->{$this->entityGetter});
}

return $this->factory->create();
}

/**
* @param Uuid|string|null $namespace
*
* @return static
*/
public function nameBased(string $entityGetter, $namespace = null): self
{
$clone = clone $this;
$clone->factory = $clone->protoFactory->nameBased($namespace);
$clone->entityGetter = $entityGetter;

return $clone;
}

/**
* @return static
*/
public function randomBased(): self
{
$clone = clone $this;
$clone->factory = $clone->protoFactory->randomBased();
$clone->entityGetter = null;

return $clone;
}

/**
* @param Uuid|string|null $node
*
* @return static
*/
public function timeBased($node = null): self
{
$clone = clone $this;
$clone->factory = $clone->protoFactory->timeBased($node);
$clone->entityGetter = null;

return $clone;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
use Doctrine\ORM\Mapping\Entity;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Doctrine\IdGenerator\UlidGenerator;
use Symfony\Component\Uid\AbstractUid;
use Symfony\Component\Uid\Factory\UlidFactory;
use Symfony\Component\Uid\Ulid;

class UlidGeneratorTest extends TestCase
Expand All @@ -25,8 +25,23 @@ public function testUlidCanBeGenerated()
$generator = new UlidGenerator();
$ulid = $generator->generate($em, new Entity());

$this->assertInstanceOf(AbstractUid::class, $ulid);
$this->assertInstanceOf(Ulid::class, $ulid);
$this->assertTrue(Ulid::isValid($ulid));
}

/**
* @requires function \Symfony\Component\Uid\Factory\UlidFactory::create
*/
public function testUlidFactory()
{
$ulid = new Ulid('00000000000000000000000000');
$em = new EntityManager();
$factory = $this->createMock(UlidFactory::class);
$factory->expects($this->any())
->method('create')
->willReturn($ulid);
$generator = new UlidGenerator($factory);

$this->assertSame($ulid, $generator->generate($em, new Entity()));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bridge\Doctrine\Tests\IdGenerator;

use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Doctrine\IdGenerator\UuidGenerator;
use Symfony\Component\Uid\Factory\UuidFactory;
use Symfony\Component\Uid\NilUuid;
use Symfony\Component\Uid\Uuid;
use Symfony\Component\Uid\UuidV4;
use Symfony\Component\Uid\UuidV6;

/**
* @requires function \Symfony\Component\Uid\Factory\UuidFactory::create
*/
class UuidGeneratorTest extends TestCase
{
public function testUuidCanBeGenerated()
{
$em = new EntityManager();
$generator = new UuidGenerator();
$uuid = $generator->generate($em, new Entity());

$this->assertInstanceOf(Uuid::class, $uuid);
}

public function testCustomUuidfactory()
{
$uuid = new NilUuid();
$em = new EntityManager();
$factory = $this->createMock(UuidFactory::class);
$factory->expects($this->any())
->method('create')
->willReturn($uuid);
$generator = new UuidGenerator($factory);

$this->assertSame($uuid, $generator->generate($em, new Entity()));
}

public function testUuidfactory()
{
$em = new EntityManager();
$generator = new UuidGenerator();
$this->assertInstanceOf(UuidV6::class, $generator->generate($em, new Entity()));

$generator = $generator->randomBased();
$this->assertInstanceOf(UuidV4::class, $generator->generate($em, new Entity()));

$generator = $generator->timeBased();
$this->assertInstanceOf(UuidV6::class, $generator->generate($em, new Entity()));

$generator = $generator->nameBased('prop1', Uuid::NAMESPACE_OID);
$this->assertEquals(Uuid::v5(new Uuid(Uuid::NAMESPACE_OID), '3'), $generator->generate($em, new Entity()));

$generator = $generator->nameBased('prop2', Uuid::NAMESPACE_OID);
$this->assertEquals(Uuid::v5(new Uuid(Uuid::NAMESPACE_OID), '2'), $generator->generate($em, new Entity()));

$generator = $generator->nameBased('getProp4', Uuid::NAMESPACE_OID);
$this->assertEquals(Uuid::v5(new Uuid(Uuid::NAMESPACE_OID), '4'), $generator->generate($em, new Entity()));

$factory = new UuidFactory(6, 6, 5, 5, null, Uuid::NAMESPACE_OID);
$generator = new UuidGenerator($factory);
$generator = $generator->nameBased('prop1');
$this->assertEquals(Uuid::v5(new Uuid(Uuid::NAMESPACE_OID), '3'), $generator->generate($em, new Entity()));
}
}

class Entity
{
public $prop1 = 1;
public $prop2 = 2;

public function prop1()
{
return 3;
}

public function getProp4()
{
return 4;
}
}
1 change: 1 addition & 0 deletions src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ CHANGELOG
* Added the `dispatcher` option to `debug:event-dispatcher`
* Added the `event_dispatcher.dispatcher` tag
* Added `assertResponseFormatSame()` in `BrowserKitAssertionsTrait`
* Add support for configuring UUID factory services

5.2.0
-----
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
use Symfony\Component\RateLimiter\Policy\TokenBucketLimiter;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Uid\Factory\UuidFactory;
use Symfony\Component\Validator\Validation;
use Symfony\Component\WebLink\HttpHeaderSerializer;
use Symfony\Component\Workflow\WorkflowEvents;
Expand Down Expand Up @@ -136,6 +137,7 @@ public function getConfigTreeBuilder()
$this->addSecretsSection($rootNode);
$this->addNotifierSection($rootNode);
$this->addRateLimiterSection($rootNode);
$this->addUidSection($rootNode);

return $treeBuilder;
}
Expand Down Expand Up @@ -1891,4 +1893,37 @@ private function addRateLimiterSection(ArrayNodeDefinition $rootNode)
->end()
;
}

private function addUidSection(ArrayNodeDefinition $rootNode)
{
$rootNode
->children()
->arrayNode('uid')
->info('Uid configuration')
->{class_exists(UuidFactory::class) ? 'canBeDisabled' : 'canBeEnabled'}()
->addDefaultsIfNotSet()
->children()
->enumNode('default_uuid_version')
->defaultValue(6)
->values([6, 4, 1])
->end()
->enumNode('name_based_uuid_version')
->defaultValue(5)
->values([5, 3])
->end()
->scalarNode('name_based_uuid_namespace')
->cannotBeEmpty()
->end()
->enumNode('time_based_uuid_version')
->defaultValue(6)
->values([6, 1])
->end()
->scalarNode('time_based_uuid_node')
->cannotBeEmpty()
->end()
->end()
->end()
->end()
;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,8 @@
use Symfony\Component\Translation\Command\XliffLintCommand as BaseXliffLintCommand;
use Symfony\Component\Translation\PseudoLocalizationTranslator;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Uid\Factory\UuidFactory;
use Symfony\Component\Uid\UuidV4;
use Symfony\Component\Validator\ConstraintValidatorInterface;
use Symfony\Component\Validator\Mapping\Loader\PropertyInfoLoader;
use Symfony\Component\Validator\ObjectInitializerInterface;
Expand Down Expand Up @@ -449,6 +451,14 @@ public function load(array $configs, ContainerBuilder $container)
$loader->load('web_link.php');
}

if ($this->isConfigEnabled($container, $config['uid'])) {
if (!class_exists(UuidFactory::class)) {
throw new LogicException('Uid support cannot be enabled as the Uid component is not installed. Try running "composer require symfony/uid".');
}

$this->registerUidConfiguration($config['uid'], $container, $loader);
}

$this->addAnnotatedClassesToCompile([
'**\\Controller\\',
'**\\Entity\\',
Expand Down Expand Up @@ -2322,6 +2332,27 @@ public static function registerRateLimiter(ContainerBuilder $container, string $
$container->registerAliasForArgument($limiterId, RateLimiterFactory::class, $name.'.limiter');
}

private function registerUidConfiguration(array $config, ContainerBuilder $container, PhpFileLoader $loader)
{
$loader->load('uid.php');

$container->getDefinition('uuid.factory')
->setArguments([
$config['default_uuid_version'],
$config['time_based_uuid_version'],
$config['name_based_uuid_version'],
UuidV4::class,
$config['time_based_uuid_node'] ?? null,
$config['name_based_uuid_namespace'] ?? null,
])
;

if (isset($config['name_based_uuid_namespace'])) {
$container->getDefinition('name_based_uuid.factory')
->setArguments([$config['name_based_uuid_namespace']]);
}
}

private function resolveTrustedHeaders(array $headers): int
{
$trustedHeaders = 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
<xsd:element name="mailer" type="mailer" minOccurs="0" maxOccurs="1" />
<xsd:element name="http-cache" type="http_cache" minOccurs="0" maxOccurs="1" />
<xsd:element name="rate-limiter" type="rate_limiter" minOccurs="0" maxOccurs="1" />
<xsd:element name="uid" type="uid" minOccurs="0" maxOccurs="1" />
</xsd:choice>

<xsd:attribute name="http-method-override" type="xsd:boolean" />
Expand Down Expand Up @@ -692,4 +693,35 @@
<xsd:attribute name="interval" type="xsd:string" />
<xsd:attribute name="amount" type="xsd:int" />
</xsd:complexType>

<xsd:complexType name="uid">
<xsd:attribute name="enabled" type="xsd:boolean" />
<xsd:attribute name="default_uuid_version" type="default_uuid_version" />
<xsd:attribute name="name_based_uuid_version" type="name_based_uuid_version" />
<xsd:attribute name="time_based_uuid_version" type="time_based_uuid_version" />
<xsd:attribute name="name_based_uuid_namespace" type="xsd:string" />
<xsd:attribute name="time_based_uuid_node" type="xsd:string" />
</xsd:complexType>

<xsd:simpleType name="default_uuid_version">
<xsd:restriction base="xsd:int">
<xsd:enumeration value="6" />
<xsd:enumeration value="4" />
<xsd:enumeration value="1" />
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name="name_based_uuid_version">
<xsd:restriction base="xsd:int">
<xsd:enumeration value="5" />
<xsd:enumeration value="3" />
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name="time_based_uuid_version">
<xsd:restriction base="xsd:int">
<xsd:enumeration value="6" />
<xsd:enumeration value="1" />
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>
Loading