Skip to content

[Validator] Add normalizer option to Unique constraint #38488

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
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
[Validator] Add normalizer option to Unique constraint
  • Loading branch information
henry2778 authored and derrabus committed Mar 18, 2021
commit 44e1e8bc9b7f1ece7f8e33e347e1fdf6c59c9cce
2 changes: 1 addition & 1 deletion src/Symfony/Component/Validator/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ CHANGELOG

5.3
---

* Add the `normalizer` option to the `Unique` constraint
* Add `Validation::createIsValidCallable()` that returns true/false instead of throwing exceptions

5.2.0
Expand Down
8 changes: 8 additions & 0 deletions src/Symfony/Component/Validator/Constraints/Unique.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\InvalidArgumentException;

/**
* @Annotation
Expand All @@ -29,15 +30,22 @@ class Unique extends Constraint
];

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

public function __construct(
array $options = null,
string $message = null,
callable $normalizer = null,
array $groups = null,
$payload = null
) {
parent::__construct($options, $groups, $payload);

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

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)));
}
}
}
14 changes: 14 additions & 0 deletions src/Symfony/Component/Validator/Constraints/UniqueValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,10 @@ public function validate($value, Constraint $constraint)
}

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

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

private function getNormalizer(Unique $unique): callable
{
if (null === $unique->normalizer) {
return static function ($value) {
return $value;
};
}

return $unique->normalizer;
}
}
27 changes: 24 additions & 3 deletions src/Symfony/Component/Validator/Tests/Constraints/UniqueTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,15 @@

use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\Constraints\Unique;
use Symfony\Component\Validator\Exception\InvalidArgumentException;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\Loader\AnnotationLoader;

/**
* @requires PHP 8
*/
class UniqueTest extends TestCase
{
/**
* @requires PHP 8
*/
public function testAttributes()
{
$metadata = new ClassMetadata(UniqueDummy::class);
Expand All @@ -34,6 +35,23 @@ public function testAttributes()
[$cConstraint] = $metadata->properties['c']->getConstraints();
self::assertSame(['my_group'], $cConstraint->groups);
self::assertSame('some attached data', $cConstraint->payload);

[$dConstraint] = $metadata->properties['d']->getConstraints();
self::assertSame('intval', $dConstraint->normalizer);
}

public function testInvalidNormalizerThrowsException()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('The "normalizer" option must be a valid callable ("string" given).');
new Unique(['normalizer' => 'Unknown Callable']);
}

public function testInvalidNormalizerObjectThrowsException()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('The "normalizer" option must be a valid callable ("stdClass" given).');
new Unique(['normalizer' => new \stdClass()]);
}
}

Expand All @@ -47,4 +65,7 @@ class UniqueDummy

#[Unique(groups: ['my_group'], payload: 'some attached data')]
private $c;

#[Unique(normalizer: 'intval')]
private $d;
}
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,136 @@ public function testInvalidValueNamed()
->setCode(Unique::IS_NOT_UNIQUE)
->assertRaised();
}

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

$object2 = new \stdClass();
$object2->name = 'Foo';
$object2->email = 'foobar@email.com';

$object3 = new \stdClass();
$object3->name = 'Bar';
$object3->email = 'foo@email.com';

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

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

$this->assertNoViolation();
}

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

$object2 = new \stdClass();
$object2->name = 'Foo';
$object2->email = 'foo@email.com';

$object3 = new \stdClass();
$object3->name = 'Foo';
$object3->email = 'foo@email.com';

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

$this->validator->validate($value, new Unique([
'message' => 'myMessage',
'normalizer' => $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()
{
$this->validator->validate([1, '1', 1.0, '1.0'], new Unique([
'message' => 'myMessage',
'normalizer' => 'intval',
]));

$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([
'normalizer' => $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',
'normalizer' => $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([
'normalizer' => $callback,
]));

$this->assertNoViolation();
}
}

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

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy