Skip to content

[Validator] Unique constraint can't be applied to collection of object #48072

Closed
@BastienRimbert

Description

@BastienRimbert

Description

In its current state, the option fields in the constraint Unique only works for a collection of array. In my case, I have an array of object and thus, it doesn't work on it.

Example

Improving the current constraint is simple : using a PropertyAccessor instead of using array access completely solve the problem without breaking current usage :

private function reduceElementKeys(array $fields, array $element): array
{
    $output = [];
    foreach ($fields as $field) {
        if (!\is_string($field)) {
            throw new UnexpectedTypeException($field, 'string');
        }

        // Using property accessor (injected in constructor?)
        if ($this->propertyAccessor->isReadable($element, $field)) {
            $output[$field] = $this->propertyAccessor->getValue($element, $field);
        }

        // Old (using array access)
        /*if (isset($element[$field])) {
            $output[$field] = $element[$field];
        }*/
    }

    return $output;
}

If the idea is validated, I'll do the request right after if needed

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