Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Validator] Add valueNormalizer option to Unique Constraint #37507

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
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/Component/Validator/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ CHANGELOG
5.2.0
-----

* added the `valueNormalizer` option to `Unique` Constraint
* added a `Cascade` constraint to ease validating nested typed object properties
* deprecated the `allowEmptyString` option of the `Length` constraint

Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Component/Validator/Constraints/Unique.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,9 @@ class Unique extends Constraint
];

public $message = 'This collection should contain only unique elements.';

/**
* @var string|callable
*/
public $valueNormalizer;
}
27 changes: 27 additions & 0 deletions src/Symfony/Component/Validator/Constraints/UniqueValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;

Expand All @@ -39,7 +40,10 @@ public function validate($value, Constraint $constraint)
}

$collectionElements = [];
$valueNormalizer = $this->getValueNormalizer($constraint);
foreach ($value as $element) {
$element = $valueNormalizer($element);

if (\in_array($element, $collectionElements, true)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
Expand All @@ -51,4 +55,27 @@ public function validate($value, Constraint $constraint)
$collectionElements[] = $element;
}
}

private function getValueNormalizer(Unique $unique)
{
$normalizer = $unique->valueNormalizer;

if (null === $normalizer) {
return static function ($value) {
return $value;
};
}

if (\is_callable($normalizer)) {
return $normalizer;
}

if (\is_array($normalizer) && !\is_callable($normalizer) && isset($normalizer[0]) && \is_object($normalizer[0])) {
$normalizer[0] = \get_class($normalizer[0]);

return $normalizer;
}

throw new ConstraintDefinitionException(json_encode($normalizer).' in Unique constraint is not a valid callable.');
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@
use Symfony\Component\Validator\Constraints\UniqueValidator;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;

class CallableClass
{
public static function execute(\stdClass $object)
{
return [$object->name, $object->email];
}
}

class UniqueValidatorTest extends ConstraintValidatorTestCase
{
protected function createValidator()
Expand Down Expand Up @@ -84,4 +92,132 @@ public function getInvalidValues()
yield 'not unique objects' => [[$object, $object]],
];
}

/**
* @dataProvider getCallback
*/
public function testExpectsUniqueObjects($callback)
{
$object1 = new \stdClass();
$object1->name = 'Foo';
$object1->email = '[email protected]';

$object2 = new \stdClass();
$object2->name = 'Foo';
$object2->email = '[email protected]';

$object3 = new \stdClass();
$object3->name = 'Bar';
$object3->email = '[email protected]';

$value = [$object1, $object2, $object3];

$this->validator->validate($value, new Unique([
'valueNormalizer' => $callback,
]));

$this->assertNoViolation();
}

/**
* @dataProvider getCallback
*/
public function testExpectsNonUniqueObjects($callback)
{
$object1 = new \stdClass();
$object1->name = 'Foo';
$object1->email = '[email protected]';

$object2 = new \stdClass();
$object2->name = 'Foo';
$object2->email = '[email protected]';

$object3 = new \stdClass();
$object3->name = 'Foo';
$object3->email = '[email protected]';

$value = [$object1, $object2, $object3];

$this->validator->validate($value, new Unique([
'message' => 'myMessage',
'valueNormalizer' => $callback,
]));

$this->buildViolation('myMessage')
->setParameter('{{ value }}', 'array')
->setCode(Unique::IS_NOT_UNIQUE)
->assertRaised();
}

public function getCallback()
{
return [
yield 'static function' => [static function (\stdClass $object) {
return [$object->name, $object->email];
}],
yield 'callable with string notation' => ['Symfony\Component\Validator\Tests\Constraints\CallableClass::execute'],
yield 'callable with static notation' => [[CallableClass::class, 'execute']],
yield 'callable with object' => [[new CallableClass(), 'execute']],
];
}

public function testExpectsInvalidNonStrictComparison()
{
$callback = static function ($item) {
return (int) $item;
};

$this->validator->validate([1, '1', 1.0, '1.0'], new Unique([
'message' => 'myMessage',
'valueNormalizer' => $callback,
]));

$this->buildViolation('myMessage')
->setParameter('{{ value }}', 'array')
->setCode(Unique::IS_NOT_UNIQUE)
->assertRaised();
}

public function testExpectsValidNonStrictComparison()
{
$callback = static function ($item) {
return (int) $item;
};

$this->validator->validate([1, '2', 3, '4.0'], new Unique([
'valueNormalizer' => $callback,
]));

$this->assertNoViolation();
}

public function testExpectsInvalidCaseInsensitiveComparison()
{
$callback = static function ($item) {
return mb_strtolower($item);
};

$this->validator->validate(['Hello', 'hello', 'HELLO', 'hellO'], new Unique([
'message' => 'myMessage',
'valueNormalizer' => $callback,
]));

$this->buildViolation('myMessage')
->setParameter('{{ value }}', 'array')
->setCode(Unique::IS_NOT_UNIQUE)
->assertRaised();
}

public function testExpectsValidCaseInsensitiveComparison()
{
$callback = static function ($item) {
return mb_strtolower($item);
};

$this->validator->validate(['Hello', 'World'], new Unique([
'valueNormalizer' => $callback,
]));

$this->assertNoViolation();
}
}