Skip to content

[Uid] add command to generate UIDs #36405

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

Closed
wants to merge 14 commits into from
Closed
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/Bundle/FrameworkBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ CHANGELOG
* Made `BrowserKitAssertionsTrait` report the original error message in case of a failure
* Added ability for `config:dump-reference` and `debug:config` to dump and debug kernel container extension configuration.
* Deprecated `session.attribute_bag` service and `session.flash_bag` service.
* The `uid:generate` command from the Uid Component is now registered.

5.0.0
-----
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@
use Symfony\Component\String\Slugger\SluggerInterface;
use Symfony\Component\Translation\Command\XliffLintCommand as BaseXliffLintCommand;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Uid\Command\UidGenerateCommand;
use Symfony\Component\Validator\ConstraintValidatorInterface;
use Symfony\Component\Validator\Mapping\Loader\PropertyInfoLoader;
use Symfony\Component\Validator\ObjectInitializerInterface;
Expand Down Expand Up @@ -187,6 +188,9 @@ public function load(array $configs, ContainerBuilder $container)
if (!class_exists(BaseYamlLintCommand::class)) {
$container->removeDefinition('console.command.yaml_lint');
}
if (!class_exists(UidGenerateCommand::class)) {
$container->removeDefinition('console.command.uid_generate');
}
}

// Load Cache configuration first as it is used by other components
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,10 @@
<tag name="console.command" command="translation:update" />
</service>

<service id="console.command.uid_generate" class="Symfony\Component\Uid\Command\UidGenerateCommand">
<tag name="console.command" command="uid:generate" />
</service>

<service id="console.command.workflow_dump" class="Symfony\Bundle\FrameworkBundle\Command\WorkflowDumpCommand">
<tag name="console.command" command="workflow:dump" />
</service>
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Component/Uid/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ CHANGELOG
* added support for UUID
* added support for ULID
* added the component
* added `uid:generate` command to generate UUIDs and ULIDs
120 changes: 120 additions & 0 deletions src/Symfony/Component/Uid/Command/UidGenerateCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
<?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\Component\Uid\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Uid\Ulid;
use Symfony\Component\Uid\Uuid;

class UidGenerateCommand extends Command
{
protected static $defaultName = 'uid:generate';

private const UUID_1 = 'uuid-1';
private const UUID_3 = 'uuid-3';
private const UUID_4 = 'uuid-4';
private const UUID_5 = 'uuid-5';
private const UUID_6 = 'uuid-6';
private const ULID = 'ulid';

private const TYPES = [
self::UUID_1,
self::UUID_3,
self::UUID_4,
self::UUID_5,
self::UUID_6,
self::ULID,
];

/**
* {@inheritdoc}
*/
protected function configure()
{
$typesAsString = implode(', ', self::TYPES);

$this
->setDefinition([
new InputArgument('type', InputArgument::REQUIRED, 'The type/version of the generated UID.'),
new InputArgument('namespace', InputArgument::OPTIONAL, 'Namespace for UUID V3 and V5 versions.', ''),
new InputArgument('name', InputArgument::OPTIONAL, 'Name for UUID V3 and V5 versions.', ''),
new InputOption('base32', null, InputOption::VALUE_NONE, 'Use this option to represent the generated UUID/ULID in base 32.'),
new InputOption('base58', null, InputOption::VALUE_NONE, 'Use this option to represent the generated UUID/ULID in base 58.'),
])
->setDescription('Generates a UID, that can be either a ULID or a UUID in a given version.')
->setHelp(<<<EOF
The <info>%command.name%</info> generates UID. This can be a ULID or a UUID
in a given version. Available types are $typesAsString.
Examples:

<info>php %command.full_name% ulid</info> for generating a ULID.
<info>php %command.full_name% uuid-1</info> for generating a UUID in version 1.
<info>php %command.full_name% uuid-3 9b7541de-6f87-11ea-ab3c-9da9a81562fc foo</info> for generating a UUID in version 3.
<info>php %command.full_name% uuid-4 --base32</info> for generating a UUID in version 4 represented in base 32.

EOF
)
;
}

/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
$type = $input->getArgument('type');
$namespace = $input->getArgument('namespace');
$name = $input->getArgument('name');

if (\in_array($type, [self::UUID_3, self::UUID_5], true) && !Uuid::isValid($namespace)) {
throw new InvalidArgumentException('You must specify a valid namespace as a second argument.');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

worth generating/outputting one? perhaps toggle name/namespace args

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mean that, in case the user hasn't provided a namespace, we should generate/output a random one?

}

switch ($type) {
case self::UUID_1:
$uid = Uuid::v1();
break;
case self::UUID_3:
$uid = Uuid::v3(Uuid::fromString($namespace), $name);
break;
case self::UUID_4:
$uid = Uuid::v4();
break;
case self::UUID_5:
$uid = Uuid::v5(Uuid::fromString($namespace), $name);
break;
case self::UUID_6:
$uid = Uuid::v6();
break;
case self::ULID:
$uid = new Ulid();
break;
default:
throw new InvalidArgumentException('Invalid UID type. Available values are '.implode(', ', self::TYPES).'.');
}

if ($input->getOption('base32')) {
$uid = $uid->toBase32();
} elseif ($input->getOption('base58')) {
$uid = $uid->toBase58();
}

$output->writeln($uid);

return 0;
}
}
49 changes: 49 additions & 0 deletions src/Symfony/Component/Uid/Tests/Command/UidGenerateCommandTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

namespace Symfony\Component\Uid\Tests\Command;

use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Component\Console\Application as BaseApplication;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\Uid\Command\UidGenerateCommand;

class UidGenerateCommandTest extends TestCase
{
public function testGenerateUid()
{
$tester = $this->getTester();

$tester->execute(['type' => 'uuid-1']);
$this->assertRegExp('/[a-f\d]{8}\-[a-f\d]{4}\-1[a-f\d]{3}\-[a-f\d]{4}\-[a-f\d]{8}/i', $tester->getDisplay());

$tester->execute(['type' => 'uuid-3', 'namespace' => 'a1dc606e-741b-11ea-aa36-99e245e7882b', 'name' => 'foo']);
$this->assertStringContainsString('ad4ab486-b67f-3d46-881f-21f03d27a68b', $tester->getDisplay());

$tester->execute(['type' => 'uuid-4']);
$this->assertRegExp('/[a-f\d]{8}\-[a-f\d]{4}\-4[a-f\d]{3}\-[a-f\d]{4}\-[a-f\d]{8}/i', $tester->getDisplay());

$tester->execute(['type' => 'uuid-5', 'namespace' => 'a1dc606e-741b-11ea-aa36-99e245e7882b', 'name' => 'foo']);
$this->assertStringContainsString('d87f160a-3cc6-520e-845f-112865bed05c', $tester->getDisplay());

$tester->execute(['type' => 'uuid-6']);
$this->assertRegExp('/[a-f\d]{8}\-[a-f\d]{4}\-6[a-f\d]{3}\-[a-f\d]{4}\-[a-f\d]{8}/i', $tester->getDisplay());

$tester->execute(['type' => 'ulid']);
$this->assertRegExp('/[0-9A-HJKMNP-TV-Z]{26}/i', $tester->getDisplay());

$tester->execute(['type' => 'uuid-1', '--base32' => true]);
$this->assertRegExp('/[0-9A-HJKMNP-TV-Z]{26}/i', $tester->getDisplay());

$tester->execute(['type' => 'uuid-1', '--base58' => true]);
$this->assertRegExp('/[1-9A-HJ-NP-Za-km-z]{22}/i', $tester->getDisplay());
}

public function getTester(): CommandTester
{
$application = new BaseApplication();
$application->add(new UidGenerateCommand());
$command = $application->find('uid:generate');

return new CommandTester($command);
}
}