Skip to content

[Validator] Add the format option to the Ulid constraint to allow accepting different ULID formats #57438

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
Jun 25, 2024
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/Component/Validator/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ CHANGELOG
* Make `PasswordStrengthValidator::estimateStrength()` public
* Add the `Yaml` constraint for validating YAML content
* Add `errorPath` to Unique constraint
* Add the `format` option to the `Ulid` constraint to allow accepting different ULID formats

7.1
---
Expand Down
12 changes: 12 additions & 0 deletions src/Symfony/Component/Validator/Constraints/Ulid.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;

/**
* Validates that a value is a valid Universally Unique Lexicographically Sortable Identifier (ULID).
Expand All @@ -35,20 +36,31 @@ class Ulid extends Constraint
self::TOO_LARGE_ERROR => 'TOO_LARGE_ERROR',
];

public const FORMAT_BASE_32 = 'base32';
public const FORMAT_BASE_58 = 'base58';

public string $message = 'This is not a valid ULID.';
public string $format = self::FORMAT_BASE_32;

/**
* @param array<string,mixed>|null $options
* @param string[]|null $groups
* @param self::FORMAT_*|null $format
*/
public function __construct(
?array $options = null,
?string $message = null,
?array $groups = null,
mixed $payload = null,
?string $format = null,
) {
parent::__construct($options, $groups, $payload);

$this->message = $message ?? $this->message;
$this->format = $format ?? $this->format;

if (!\in_array($this->format, [self::FORMAT_BASE_32, self::FORMAT_BASE_58], true)) {
throw new ConstraintDefinitionException(sprintf('The "%s" validation format is not supported.', $format));
}
}
}
40 changes: 28 additions & 12 deletions src/Symfony/Component/Validator/Constraints/UlidValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,31 +40,47 @@ public function validate(mixed $value, Constraint $constraint): void

$value = (string) $value;

if (26 !== \strlen($value)) {
[$requiredLength, $requiredCharset] = match ($constraint->format) {
Ulid::FORMAT_BASE_32 => [26, '0123456789ABCDEFGHJKMNPQRSTVWXYZabcdefghjkmnpqrstvwxyz'],
Ulid::FORMAT_BASE_58 => [22, '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'],
};

if ($requiredLength !== \strlen($value)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->setCode(26 > \strlen($value) ? Ulid::TOO_SHORT_ERROR : Ulid::TOO_LONG_ERROR)
->setParameters([
'{{ value }}' => $this->formatValue($value),
'{{ format }}' => $constraint->format,
])
->setCode($requiredLength > \strlen($value) ? Ulid::TOO_SHORT_ERROR : Ulid::TOO_LONG_ERROR)
->addViolation();

return;
}

if (\strlen($value) !== strspn($value, '0123456789ABCDEFGHJKMNPQRSTVWXYZabcdefghjkmnpqrstvwxyz')) {
if (\strlen($value) !== strspn($value, $requiredCharset)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->setParameters([
'{{ value }}' => $this->formatValue($value),
'{{ format }}' => $constraint->format,
])
->setCode(Ulid::INVALID_CHARACTERS_ERROR)
->addViolation();

return;
}

// Largest valid ULID is '7ZZZZZZZZZZZZZZZZZZZZZZZZZ'
// Cf https://github.com/ulid/spec#overflow-errors-when-parsing-base32-strings
if ($value[0] > '7') {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->setCode(Ulid::TOO_LARGE_ERROR)
->addViolation();
if (Ulid::FORMAT_BASE_32 === $constraint->format) {
// Largest valid ULID is '7ZZZZZZZZZZZZZZZZZZZZZZZZZ'
// Cf https://github.com/ulid/spec#overflow-errors-when-parsing-base32-strings
if ($value[0] > '7') {
$this->context->buildViolation($constraint->message)
->setParameters([
'{{ value }}' => $this->formatValue($value),
'{{ format }}' => $constraint->format,
])
->setCode(Ulid::TOO_LARGE_ERROR)
->addViolation();
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\Constraints\Ulid;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\Loader\AttributeLoader;

Expand All @@ -32,6 +33,14 @@ public function testAttributes()
self::assertSame(['my_group'], $cConstraint->groups);
self::assertSame('some attached data', $cConstraint->payload);
}

public function testUnexpectedValidationFormat()
{
$this->expectException(ConstraintDefinitionException::class);
$this->expectExceptionMessage('The "invalid" validation format is not supported.');

new Ulid(format: 'invalid');
}
}

class UlidDummy
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,13 @@ public function testValidUlid()
$this->assertNoViolation();
}

public function testValidUlidAsBase58()
{
$this->validator->validate('1CCD2w4mK2m455S2BAXFht', new Ulid(format: Ulid::FORMAT_BASE_58));

$this->assertNoViolation();
}

/**
* @dataProvider getInvalidUlids
*/
Expand All @@ -65,12 +72,15 @@ public function testInvalidUlid(string $ulid, string $code)
$this->validator->validate($ulid, $constraint);

$this->buildViolation('testMessage')
->setParameter('{{ value }}', '"'.$ulid.'"')
->setParameters([
'{{ value }}' => '"'.$ulid.'"',
'{{ format }}' => Ulid::FORMAT_BASE_32,
])
->setCode($code)
->assertRaised();
}

public static function getInvalidUlids()
public static function getInvalidUlids(): array
{
return [
['01ARZ3NDEKTSV4RRFFQ69G5FA', Ulid::TOO_SHORT_ERROR],
Expand All @@ -81,14 +91,45 @@ public static function getInvalidUlids()
];
}

/**
* @dataProvider getInvalidBase58Ulids
*/
public function testInvalidBase58Ulid(string $ulid, string $code)
{
$constraint = new Ulid(message: 'testMessage', format: Ulid::FORMAT_BASE_58);

$this->validator->validate($ulid, $constraint);

$this->buildViolation('testMessage')
->setParameters([
'{{ value }}' => '"'.$ulid.'"',
'{{ format }}' => Ulid::FORMAT_BASE_58,
])
->setCode($code)
->assertRaised();
}

public static function getInvalidBase58Ulids(): array
{
return [
['1CCD2w4mK2m455S2BAXFh', Ulid::TOO_SHORT_ERROR],
['1CCD2w4mK2m455S2BAXFhttt', Ulid::TOO_LONG_ERROR],
['1CCD2w4mK2m455S2BAXFhO', Ulid::INVALID_CHARACTERS_ERROR],
['not-even-ulid-like', Ulid::TOO_SHORT_ERROR],
];
}

public function testInvalidUlidNamed()
{
$constraint = new Ulid(message: 'testMessage');

$this->validator->validate('01ARZ3NDEKTSV4RRFFQ69G5FA', $constraint);

$this->buildViolation('testMessage')
->setParameter('{{ value }}', '"01ARZ3NDEKTSV4RRFFQ69G5FA"')
->setParameters([
'{{ value }}' => '"01ARZ3NDEKTSV4RRFFQ69G5FA"',
'{{ format }}' => Ulid::FORMAT_BASE_32,
])
->setCode(Ulid::TOO_SHORT_ERROR)
->assertRaised();
}
Expand Down
Loading