Use UniqueEntity outside of entity and without forms

Viewed 2445

I need to validate an email passed by user:

private function validate($value): bool
{
    $violations = $this->validator->validate($value, [
        new Assert\NotBlank(),
        new Assert\Email(),
        new UniqueEntity([
            'entityClass' => User::class,
            'fields' => 'email',
        ])
    ]);

    return count($violations) === 0;
}

But UniqueEntity constraint throws an exception:

Warning: get_class() expects parameter 1 to be object, string given

Seems like ValidatorInterface::validate() method's first argument awaiting for Entity object with getEmail() method, but it looks ugly.

Is there any elegant way to validate uniqueness of field passing only scalar value to ValidatorInterface::validate() method?

2 Answers
Related