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

Skip to content

[Validator] Unique Validator possible improvement #37451

Closed
@henry2778

Description

@henry2778

Description
I have a suggestion regarding the Unique Validator - i.e the comparison of elements. The thing that I have faced, is that when validating the collection of objects we often want to check the uniqueness not in the 'in array strict' sense, but more business logic sense. For example, I would like to check that my Category has Collection of unique Books. Then the Unique Validator will pass, because I have physically different objects there. But what is needed - is to check if they have different Titles for example. So maybe it would better if we could apply some context to the comparison.

For example, we could pass some callable in constraint, that will be applied to each element of iterable (basically we can call it normalizer). This can give us more flexibility not only for comparing objects, but other types too. That normalizer is trivial by default of course - so no BC breaks

WDYT? The reason opened that issue is that we had to create basically the same validator as UniqueValidator, with 90% same codebase in 2 projects already :)

I would like to work on that if that makes sense

Example

Tweaking https://github.com/symfony/symfony/blob/master/src/Symfony/Component/Validator/Constraints/UniqueValidator.php#L42
as follows

        $normalizer = $constraint->normalizer;
        foreach ($value as $element) {
           
            $element = $normalizer($element);

            if (\in_array($element, $collectionElements, true)) {
                $this->context->buildViolation($constraint->message)
                    ->setParameter('{{ value }}', $this->formatValue($value))
                    ->setCode(Unique::IS_NOT_UNIQUE)
                    ->addViolation();

                return;
            }
            $collectionElements[] = $element;
        }

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions