8000 [Validator] Define which collection keys should be checked for uniqueness by wkania · Pull Request #42403 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Validator] Define which collection keys should be checked for uniqueness #42403

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 12 commits into from
Prev Previous commit
Next Next commit
Add unique validator logic
  • Loading branch information
wkania committed Apr 3, 2022
commit ebea7e849acd361b4c1f4e1cee87c3154c68de77
19 changes: 19 additions & 0 deletions src/Symfony/Component/Validator/Constraints/UniqueValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,13 @@ public function validate(mixed $value, Constraint $constraint)
$collectionElements = [];
$normalizer = $this->getNormalizer($constraint);
foreach ($value as $element) {
if (!empty($fields)) {
$element = $this->reduceElementKeys($fields, $element);
if (empty($element)) {
continue;
}
}

$element = $normalizer($element);

if (\in_array($element, $collectionElements, true)) {
Expand All @@ -71,4 +78,16 @@ private function getNormalizer(Unique $unique): callable

return $unique->normalizer;
}

private function reduceElementKeys(array $fields, array $element): array
{
$output = [];
foreach ($fields as $field) {
if (isset($element[$field])) {
$output[$field] = $element[$field];
}
}

return $output;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,37 @@ public function getValidCollectionValues()
yield 'unique objects' => [[['object' => new \stdClass()], ['object' => new \stdClass()]], ['object']],
];
}

/**
* @dataProvider getInvalidCollectionValues
*/
public function testInvalidCollectionValues($value, $fields)
{
$this->validator->validate($value, new Unique($fields, [
'message' => 'myMessage',
]));

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

public function getInvalidCollectionValues()
{
return [
yield 'unique string' => [[['lang' => 'eng', 'translation' => 'hi'], ['lang' => 'eng', 'translation' => 'hi'],
], ['lang']],
yield 'unique floats' => [[
['latitude' => 51.509865, 'longitude' => -0.118092, 'poi' => 'capital'],
['latitude' => 52.520008, 'longitude' => 13.404954],
['latitude' => 51.509865, 'longitude' => -0.118092],
], ['latitude', 'longitude']],
yield 'unique int' => [[
['id' => 1, 'email' => 'bar@email.com'], ['id' => 1, 'email' => 'bar@email.com'],
], ['id']],
];
}
}

class CallableClass
Expand Down
0