Skip to content

[Validator] Implement countUnit option for Length constraint #49464

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 21, 2023
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
* Add `Uuid::TIME_BASED_VERSIONS` to match that a UUID being validated embeds a timestamp
* Add the `pattern` parameter in violations of the `Regex` constraint
* Add a `NoSuspiciousCharacters` constraint to validate a string is not a spoofing attempt
* Add the `countUnit` option to the `Length` constraint to allow counting the string length either by code points (like before, now the default setting `Length::COUNT_CODEPOINTS`), bytes (`Length::COUNT_BYTES`) or graphemes (`Length::COUNT_GRAPHEMES`)

6.2
---
Expand Down
21 changes: 21 additions & 0 deletions src/Symfony/Component/Validator/Constraints/Length.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,16 @@ class Length extends Constraint
self::INVALID_CHARACTERS_ERROR => 'INVALID_CHARACTERS_ERROR',
];

public const COUNT_BYTES = 'bytes';
public const COUNT_CODEPOINTS = 'codepoints';
public const COUNT_GRAPHEMES = 'graphemes';

private const VALID_COUNT_UNITS = [
self::COUNT_BYTES,
self::COUNT_CODEPOINTS,
self::COUNT_GRAPHEMES,
];

/**
* @deprecated since Symfony 6.1, use const ERROR_NAMES instead
*/
Expand All @@ -49,13 +59,19 @@ class Length extends Constraint
public $min;
public $charset = 'UTF-8';
public $normalizer;
/* @var self::COUNT_* */
public string $countUnit = self::COUNT_CODEPOINTS;

/**
* @param self::COUNT_*|null $countUnit
*/
public function __construct(
int|array $exactly = null,
int $min = null,
int $max = null,
string $charset = null,
callable $normalizer = null,
string $countUnit = null,
string $exactMessage = null,
string $minMessage = null,
string $maxMessage = null,
Expand Down Expand Up @@ -84,6 +100,7 @@ public function __construct(
$this->max = $max;
$this->charset = $charset ?? $this->charset;
$this->normalizer = $normalizer ?? $this->normalizer;
$this->countUnit = $countUnit ?? $this->countUnit;
$this->exactMessage = $exactMessage ?? $this->exactMessage;
$this->minMessage = $minMessage ?? $this->minMessage;
$this->maxMessage = $maxMessage ?? $this->maxMessage;
Expand All @@ -96,5 +113,9 @@ public function __construct(
if (null !== $this->normalizer && !\is_callable($this->normalizer)) {
throw new InvalidArgumentException(sprintf('The "normalizer" option must be a valid callable ("%s" given).', get_debug_type($this->normalizer)));
}

if (!\in_array($this->countUnit, self::VALID_COUNT_UNITS)) {
throw new InvalidArgumentException(sprintf('The "countUnit" option must be one of the "%s"::COUNT_* constants ("%s" given).', __CLASS__, $this->countUnit));
}
}
}
10 changes: 7 additions & 3 deletions src/Symfony/Component/Validator/Constraints/LengthValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,13 @@ public function validate(mixed $value, Constraint $constraint)
$invalidCharset = true;
}

if ($invalidCharset) {
$length = $invalidCharset ? 0 : match ($constraint->countUnit) {
Length::COUNT_BYTES => \strlen($stringValue),
Length::COUNT_CODEPOINTS => mb_strlen($stringValue, $constraint->charset),
Length::COUNT_GRAPHEMES => grapheme_strlen($stringValue),
};

if ($invalidCharset || false === ($length ?? false)) {
$this->context->buildViolation($constraint->charsetMessage)
->setParameter('{{ value }}', $this->formatValue($stringValue))
->setParameter('{{ charset }}', $constraint->charset)
Expand All @@ -65,8 +71,6 @@ public function validate(mixed $value, Constraint $constraint)
return;
}

$length = mb_strlen($stringValue, $constraint->charset);

if (null !== $constraint->max && $length > $constraint->max) {
$exactlyOptionEnabled = $constraint->min == $constraint->max;

Expand Down
19 changes: 19 additions & 0 deletions src/Symfony/Component/Validator/Tests/Constraints/LengthTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,25 @@ public function testInvalidNormalizerObjectThrowsException()
new Length(['min' => 0, 'max' => 10, 'normalizer' => new \stdClass()]);
}

public function testDefaultCountUnitIsUsed()
{
$length = new Length(['min' => 0, 'max' => 10]);
$this->assertSame(Length::COUNT_CODEPOINTS, $length->countUnit);
}

public function testNonDefaultCountUnitCanBeSet()
{
$length = new Length(['min' => 0, 'max' => 10, 'countUnit' => Length::COUNT_GRAPHEMES]);
$this->assertSame(Length::COUNT_GRAPHEMES, $length->countUnit);
}

public function testInvalidCountUnitThrowsException()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(sprintf('The "countUnit" option must be one of the "%s"::COUNT_* constants ("%s" given).', Length::class, 'nonExistentCountUnit'));
new Length(['min' => 0, 'max' => 10, 'countUnit' => 'nonExistentCountUnit']);
}

public function testConstraintDefaultOption()
{
$constraint = new Length(5);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@

class LengthValidatorTest extends ConstraintValidatorTestCase
{
// 🧚‍♀️ "Woman Fairy" emoji ZWJ sequence
private const SINGLE_GRAPHEME_WITH_FOUR_CODEPOINTS_AND_THIRTEEN_BYTES = "\u{1F9DA}\u{200D}\u{2640}\u{FE0F}";

protected function createValidator(): LengthValidator
{
return new LengthValidator();
Expand Down Expand Up @@ -156,6 +159,30 @@ public function testValidNormalizedValues($value)
$this->assertNoViolation();
}

public function testValidGraphemesValues()
{
$constraint = new Length(min: 1, max: 1, countUnit: Length::COUNT_GRAPHEMES);
$this->validator->validate(self::SINGLE_GRAPHEME_WITH_FOUR_CODEPOINTS_AND_THIRTEEN_BYTES, $constraint);

$this->assertNoViolation();
}

public function testValidCodepointsValues()
{
$constraint = new Length(min: 4, max: 4, countUnit: Length::COUNT_CODEPOINTS);
$this->validator->validate(self::SINGLE_GRAPHEME_WITH_FOUR_CODEPOINTS_AND_THIRTEEN_BYTES, $constraint);

$this->assertNoViolation();
}

public function testValidBytesValues()
{
$constraint = new Length(min: 13, max: 13, countUnit: Length::COUNT_BYTES);
$this->validator->validate(self::SINGLE_GRAPHEME_WITH_FOUR_CODEPOINTS_AND_THIRTEEN_BYTES, $constraint);

$this->assertNoViolation();
}

/**
* @dataProvider getThreeOrLessCharacters
*/
Expand Down Expand Up @@ -321,4 +348,34 @@ public function testOneCharset($value, $charset, $isValid)
->assertRaised();
}
}

public function testInvalidValuesExactDefaultCountUnitWithGraphemeInput()
{
$constraint = new Length(min: 1, max: 1, exactMessage: 'myMessage');

$this->validator->validate(self::SINGLE_GRAPHEME_WITH_FOUR_CODEPOINTS_AND_THIRTEEN_BYTES, $constraint);

$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.self::SINGLE_GRAPHEME_WITH_FOUR_CODEPOINTS_AND_THIRTEEN_BYTES.'"')
->setParameter('{{ limit }}', 1)
->setInvalidValue(self::SINGLE_GRAPHEME_WITH_FOUR_CODEPOINTS_AND_THIRTEEN_BYTES)
->setPlural(1)
->setCode(Length::NOT_EQUAL_LENGTH_ERROR)
->assertRaised();
}

public function testInvalidValuesExactBytesCountUnitWithGraphemeInput()
{
$constraint = new Length(min: 1, max: 1, countUnit: Length::COUNT_BYTES, exactMessage: 'myMessage');

$this->validator->validate(self::SINGLE_GRAPHEME_WITH_FOUR_CODEPOINTS_AND_THIRTEEN_BYTES, $constraint);

$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.self::SINGLE_GRAPHEME_WITH_FOUR_CODEPOINTS_AND_THIRTEEN_BYTES.'"')
->setParameter('{{ limit }}', 1)
->setInvalidValue(self::SINGLE_GRAPHEME_WITH_FOUR_CODEPOINTS_AND_THIRTEEN_BYTES)
->setPlural(1)
->setCode(Length::NOT_EQUAL_LENGTH_ERROR)
->assertRaised();
}
}