Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[FWB][Serializer][Form][Validator] Uid integration #36317

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 33 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 1 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.
* Added `uid:generate` command

5.0.0
-----
Expand Down
139 changes: 139 additions & 0 deletions 139 src/Symfony/Bundle/FrameworkBundle/Command/UidGenerateCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
<?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\Bundle\FrameworkBundle\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Uid\AbstractUid;
use Symfony\Component\Uid\Ulid;
use Symfony\Component\Uid\Uuid;

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

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

private static $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::OPTIONAL, 'The type/version of the generated UID.', null),
new InputArgument('namespace', InputArgument::OPTIONAL, 'Namespace for UUID V3 and V5 versions.', null),
new InputArgument('name', InputArgument::OPTIONAL, 'Name for UUID V3 and V5 versions.', null),
])
->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% 1</info> for generating a UUID in version 1.
<info>php %command.full_name% 3 9b7541de-6f87-11ea-ab3c-9da9a81562fc foo</info> for generating a UUID in version 3.

EOF
)
;
}

/**
* {@inheritdoc}
*
* @throws \LogicException
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);

if (!class_exists(AbstractUid::class)) {
throw new \RuntimeException('Unable to execute this command as the Symfony Uid Component is not installed.');
Copy link
Contributor

Choose a reason for hiding this comment

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

You should remove the service in the FrameworkExtension file when the AbstractUid doesn't exist instead of throwing an exception

}

$type = $input->getArgument('type') ? strtolower($input->getArgument('type')) : null;
$namespace = $input->getArgument('namespace');
$name = $input->getArgument('name');

if (null === $type || !\in_array($type, self::$types, true)) {
$type = $io->ask('Type/version of the UID. Available values are '.implode(', ', self::$types).'.', null, function ($type) {
$type = strtolower($type);
if (!\in_array($type, self::$types, true)) {
throw new \RuntimeException('Available values are '.implode(', ', self::$types).'.');
}

return $type;
});
}

if (\in_array($type, [self::UUID_3, self::UUID_5], true) && (null === $namespace || !Uuid::isValid($namespace))) {
$namespace = $io->ask('Please enter a valid namespace:', null, function ($namespace) {
if (null === $namespace || !Uuid::isValid($namespace)) {
throw new \RuntimeException('This is not a valid namespace.');
}

return $namespace;
});
}

if (\in_array($type, [self::UUID_3, self::UUID_5], true) && empty($name)) {
$name = $io->ask('Please enter a name. Press Enter for an empty string. ', '');
}

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;
}

$io->title('Generated UID:');
$io->text($uid);

return 0;
}
}
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\Bundle\FrameworkBundle\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
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,11 @@
<tag name="serializer.normalizer" priority="-890" />
</service>

<service id="serializer.normalizer.uid" class="Symfony\Component\Serializer\Normalizer\UidNormalizer">
<!-- Run before serializer.normalizer.object -->
<tag name="serializer.normalizer" priority="-90" />
</service>

<service id="serializer.normalizer.object" class="Symfony\Component\Serializer\Normalizer\ObjectNormalizer">
<argument type="service" id="serializer.mapping.class_metadata_factory" />
<argument type="service" id="serializer.name_converter.metadata_aware" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace Symfony\Bundle\FrameworkBundle\Tests\Command;

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

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

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

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

$tester->execute(['type' => '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-Z]{26}/i', $tester->getDisplay());
}

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

return new CommandTester($command);
}
}
1 change: 1 addition & 0 deletions 1 src/Symfony/Component/Form/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ CHANGELOG
* Implementing the `FormConfigBuilderInterface` without implementing the `setIsEmptyCallback()` method
is deprecated. The method will be added to the interface in 6.0.
* Added a `rounding_mode` option for the PercentType and correctly round the value when submitted
* Added `UidToStringTransformer` and `UidType`

5.0.0
-----
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?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\Form\Extension\Core\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\Uid\AbstractUid;
use Symfony\Component\Uid\Ulid;
use Symfony\Component\Uid\Uuid;

class UidToStringTransformer implements DataTransformerInterface
{
/**
* @param AbstractUid $uid An \AbstractUid object
*
* @return string|null A string representation of UUID or a ULID
*
* @throws TransformationFailedException If the given value is not a \AbstractUid
*/
public function transform($uid)
{
if (null === $uid) {
return '';
}

if (!$uid instanceof AbstractUid) {
throw new TransformationFailedException('Expected an \AbstractUid.');
}

return (string) $uid;
}

/**
* @param string $value A string representation of UUID or a ULID
*
* @return AbstractUid|null An instance of AbstractUid
*
* @throws TransformationFailedException If the given value is not a string, or could not be transformed
*/
public function reverseTransform($value)
{
if (empty($value)) {
return null;
}

if (!\is_string($value)) {
throw new TransformationFailedException('Expected a string.');
}

if (Uuid::isValid($value)) {
return Uuid::fromString($value);
}

if (Ulid::isValid($value)) {
return Ulid::fromString($value);
}

throw new TransformationFailedException('This value is not a valid string representation of a UUID or ULID.');
}
}
54 changes: 54 additions & 0 deletions 54 src/Symfony/Component/Form/Extension/Core/Type/UidType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?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\Form\Extension\Core\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\DataTransformer\UidToStringTransformer;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints as Assert;

class UidType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addViewTransformer(new UidToStringTransformer());
}

/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'constraints' => [
new Assert\Uid(),
],
]);
}

/**
* {@inheritdoc}
*/
public function getParent()
{
return TextType::class;
}

/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'uid';
}
}
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.