Skip to content

[Uid] Add Generate and Inspect commands #39883

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 25, 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
12 changes: 6 additions & 6 deletions src/Symfony/Component/Serializer/Normalizer/UidNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ final class UidNormalizer implements NormalizerInterface, DenormalizerInterface,
public const NORMALIZATION_FORMAT_KEY = 'uid_normalization_format';

public const NORMALIZATION_FORMAT_CANONICAL = 'canonical';
public const NORMALIZATION_FORMAT_BASE_58 = 'base_58';
public const NORMALIZATION_FORMAT_BASE_32 = 'base_32';
public const NORMALIZATION_FORMAT_RFC_4122 = 'rfc_4122';
public const NORMALIZATION_FORMAT_BASE58 = 'base58';
public const NORMALIZATION_FORMAT_BASE32 = 'base32';
public const NORMALIZATION_FORMAT_RFC4122 = 'rfc4122';
Copy link
Contributor

Choose a reason for hiding this comment

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

i feel like we should move the consts to AbstractUid

Copy link
Member

@nicolas-grekas nicolas-grekas Feb 23, 2021

Choose a reason for hiding this comment

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

Why? AbstractUid nor the Uid component wouldn't use them anywhere.

Copy link
Contributor

@ro0NL ro0NL Feb 23, 2021

Choose a reason for hiding this comment

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

because the formats are leaking now: The ULID output format: base32, base58 or rfc4122

Copy link
Member

@nicolas-grekas nicolas-grekas Feb 23, 2021

Choose a reason for hiding this comment

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

I think these consts in Serializer are legit.
Then, the duplication in Uid is legit also - these are from different domains.
Also, the commands (on the cli), use inline values.
In the end, these consts in Uid won't serve any purpose for the devs.
They would actually make the public API of the component more complex to me.
I'd prefer not to add them as you might have understood :)

Copy link
Contributor

Choose a reason for hiding this comment

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

i think both serializer+console are duplicating what could be AbstractUid::toFormat($format)

Copy link
Member

@nicolas-grekas nicolas-grekas Feb 23, 2021

Choose a reason for hiding this comment

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

Oh, then I'd recommend splitting this discussion into a separate PR or issue.


private $defaultContext = [
self::NORMALIZATION_FORMAT_KEY => self::NORMALIZATION_FORMAT_CANONICAL,
Expand All @@ -45,11 +45,11 @@ public function normalize($object, string $format = null, array $context = [])
switch ($context[self::NORMALIZATION_FORMAT_KEY] ?? $this->defaultContext[self::NORMALIZATION_FORMAT_KEY]) {
case self::NORMALIZATION_FORMAT_CANONICAL:
return (string) $object;
case self::NORMALIZATION_FORMAT_BASE_58:
case self::NORMALIZATION_FORMAT_BASE58:
return $object->toBase58();
case self::NORMALIZATION_FORMAT_BASE_32:
case self::NORMALIZATION_FORMAT_BASE32:
return $object->toBase32();
case self::NORMALIZATION_FORMAT_RFC_4122:
case self::NORMALIZATION_FORMAT_RFC4122:
return $object->toRfc4122();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public function testSupportsNormalization()

public function normalizeProvider()
{
$uidFormats = [null, 'canonical', 'base_58', 'base_32', 'rfc_4122'];
$uidFormats = [null, 'canonical', 'base58', 'base32', 'rfc4122'];
$data = [
[
UuidV1::fromString('9b7541de-6f87-11ea-ab3c-9da9a81562fc'),
Expand Down Expand Up @@ -149,7 +149,7 @@ public function testDenormalize($uuidString, $class)
public function testNormalizeWithNormalizationFormatPassedInConstructor()
{
$uidNormalizer = new UidNormalizer([
'uid_normalization_format' => 'rfc_4122',
'uid_normalization_format' => 'rfc4122',
]);
$ulid = Ulid::fromString('01ETWV01C0GYQ5N92ZK7QRGB10');

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 @@ -9,6 +9,7 @@ CHANGELOG
* [BC BREAK] Replace `UuidV1::getTime()`, `UuidV6::getTime()` and `Ulid::getTime()` by `UuidV1::getDateTime()`, `UuidV6::getDateTime()` and `Ulid::getDateTime()`
* Add `Uuid::NAMESPACE_*` constants from RFC4122
* Add `UlidFactory`, `UuidFactory`, `RandomBasedUuidFactory`, `TimeBasedUuidFactory` and `NameBasedUuidFactory`
* Add commands to generate and inspect UUIDs and ULIDs

5.2.0
-----
Expand Down
109 changes: 109 additions & 0 deletions src/Symfony/Component/Uid/Command/GenerateUlidCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
<?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\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Uid\Factory\UlidFactory;

class GenerateUlidCommand extends Command
{
protected static $defaultName = 'ulid:generate';
protected static $defaultDescription = 'Generates a ULID';

private $factory;

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

parent::__construct();
}

/**
* {@inheritdoc}
*/
protected function configure(): void
{
$this
->setDefinition([
new InputOption('time', null, InputOption::VALUE_REQUIRED, 'The ULID timestamp: a parsable date/time string'),
new InputOption('count', 'c', InputOption::VALUE_REQUIRED, 'The number of ULID to generate', 1),
new InputOption('format', 'f', InputOption::VALUE_REQUIRED, 'The ULID output format: base32, base58 or rfc4122', 'base32'),
])
->setDescription(self::$defaultDescription)
->setHelp(<<<'EOF'
The <info>%command.name%</info> command generates a ULID.

<info>php %command.full_name%</info>

To specify the timestamp:

<info>php %command.full_name% --time="2021-02-16 14:09:08"</info>

To generate several ULIDs:

<info>php %command.full_name% --count=10</info>

To output a specific format:

<info>php %command.full_name% --format=rfc4122</info>
EOF
)
;
}

/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$io = new SymfonyStyle($input, $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output);

if (null !== $time = $input->getOption('time')) {
try {
$time = new \DateTimeImmutable($time);
} catch (\Exception $e) {
$io->error(sprintf('Invalid timestamp "%s": %s', $time, str_replace('DateTimeImmutable::__construct(): ', '', $e->getMessage())));

return 1;
}
}

switch ($input->getOption('format')) {
case 'base32': $format = 'toBase32'; break;
case 'base58': $format = 'toBase58'; break;
case 'rfc4122': $format = 'toRfc4122'; break;
default:
$io->error(sprintf('Invalid format "%s", did you mean "base32", "base58" or "rfc4122"?', $input->getOption('format')));

return 1;
}

$count = (int) $input->getOption('count');
try {
for ($i = 0; $i < $count; ++$i) {
$output->writeln($this->factory->create($time)->$format());
}
} catch (\Exception $e) {
$io->error($e->getMessage());

return 1;
}

return 0;
}
}
200 changes: 200 additions & 0 deletions src/Symfony/Component/Uid/Command/GenerateUuidCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
<?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\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Uid\Factory\UuidFactory;
use Symfony\Component\Uid\Uuid;

class GenerateUuidCommand extends Command
{
protected static $defaultName = 'uuid:generate';
protected static $defaultDescription = 'Generates a UUID';

private $factory;

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

parent::__construct();
}

/**
* {@inheritdoc}
*/
protected function configure(): void
{
$this
->setDefinition([
new InputOption('time-based', null, InputOption::VALUE_REQUIRED, 'The timestamp, to generate a time-based UUID: a parsable date/time string'),
new InputOption('node', null, InputOption::VALUE_REQUIRED, 'The UUID whose node part should be used as the node of the generated UUID'),
new InputOption('name-based', null, InputOption::VALUE_REQUIRED, 'The name, to generate a name-based UUID'),
new InputOption('namespace', null, InputOption::VALUE_REQUIRED, 'The UUID to use at the namespace for named-based UUIDs'),
new InputOption('random-based', null, InputOption::VALUE_NONE, 'To generate a random-based UUID'),
new InputOption('count', 'c', InputOption::VALUE_REQUIRED, 'The number of UUID to generate', 1),
new InputOption('format', 'f', InputOption::VALUE_REQUIRED, 'The UUID output format: rfc4122, base58 or base32', 'rfc4122'),
])
->setDescription(self::$defaultDescription)
->setHelp(<<<'EOF'
The <info>%command.name%</info> generates a UUID.

<info>php %command.full_name%</info>

To generate a time-based UUID:

<info>php %command.full_name% --time-based=now</info>

To specify a time-based UUID's node:

<info>php %command.full_name% --time-based=@1613480254 --node=fb3502dc-137e-4849-8886-ac90d07f64a7</info>

To generate a name-based UUID:

<info>php %command.full_name% --name-based=foo</info>

To specify a name-based UUID's namespace:

<info>php %command.full_name% --name-based=bar --namespace=fb3502dc-137e-4849-8886-ac90d07f64a7</info>

To generate a random-based UUID:

<info>php %command.full_name% --random-based</info>

To generate several UUIDs:

<info>php %command.full_name% --count=10</info>

To output a specific format:

<info>php %command.full_name% --format=base58</info>
EOF
)
;
}

/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$io = new SymfonyStyle($input, $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output);

$time = $input->getOption('time-based');
$node = $input->getOption('node');
$name = $input->getOption('name-based');
$namespace = $input->getOption('namespace');
$random = $input->getOption('random-based');

if (false !== ($time ?? $name ?? $random) && 1 < ((null !== $time) + (null !== $name) + $random)) {
$io->error('Only one of "--time-based", "--name-based" or "--random-based" can be provided at a time.');

return 1;
}

if (null === $time && null !== $node) {
$io->error('Option "--node" can only be used with "--time-based".');

return 1;
}

if (null === $name && null !== $namespace) {
$io->error('Option "--namespace" can only be used with "--name-based".');

return 1;
}

switch (true) {
case null !== $time:
if (null !== $node) {
try {
$node = Uuid::fromString($node);
} catch (\InvalidArgumentException $e) {
$io->error(sprintf('Invalid node "%s": %s', $node, $e->getMessage()));

return 1;
}
}

try {
$time = new \DateTimeImmutable($time);
} catch (\Exception $e) {
$io->error(sprintf('Invalid timestamp "%s": %s', $time, str_replace('DateTimeImmutable::__construct(): ', '', $e->getMessage())));

return 1;
}

$create = function () use ($node, $time): Uuid {
return $this->factory->timeBased($node)->create($time);
};
break;

case null !== $name:
if ($namespace) {
try {
$namespace = Uuid::fromString($namespace);
} catch (\InvalidArgumentException $e) {
$io->error(sprintf('Invalid namespace "%s": %s', $namespace, $e->getMessage()));

return 1;
}
}

$create = function () use ($namespace, $name): Uuid {
try {
$factory = $this->factory->nameBased($namespace);
} catch (\LogicException $e) {
throw new \InvalidArgumentException('Missing namespace: use the "--namespace" option or configure a default namespace in the underlying factory.');
}

return $factory->create($name);
};
break;

case $random:
$create = [$this->factory->randomBased(), 'create'];
break;

default:
$create = [$this->factory, 'create'];
break;
}

switch ($input->getOption('format')) {
case 'base32': $format = 'toBase32'; break;
case 'base58': $format = 'toBase58'; break;
case 'rfc4122': $format = 'toRfc4122'; break;
default:
$io->error(sprintf('Invalid format "%s", did you mean "base32", "base58" or "rfc4122"?', $input->getOption('format')));

return 1;
}

$count = (int) $input->getOption('count');
try {
for ($i = 0; $i < $count; ++$i) {
$output->writeln($create()->$format());
}
} catch (\Exception $e) {
$io->error($e->getMessage());

return 1;
}

return 0;
}
}
Loading