prevent email or username from being non-unique (#2730)
This commit is contained in:
@@ -44,28 +44,41 @@ class UserValidator extends ConstraintValidator
|
||||
|
||||
protected function validateUser(UserEntity $user, ExecutionContextInterface $context)
|
||||
{
|
||||
$matchedEmail = false;
|
||||
if ($user->getEmail() !== null) {
|
||||
$existingByEmail = $this->userService->findUserByEmail($user->getEmail());
|
||||
|
||||
if (null !== $existingByEmail && $user->getId() !== $existingByEmail->getId()) {
|
||||
$context->buildViolation(User::getErrorName(User::USER_EXISTING_EMAIL))
|
||||
->atPath('email')
|
||||
->setTranslationDomain('validators')
|
||||
->setCode(User::USER_EXISTING_EMAIL)
|
||||
->addViolation();
|
||||
}
|
||||
$this->validateEmailExists($user->getId(), $user->getEmail(), 'email', User::USER_EXISTING_EMAIL, $context);
|
||||
$this->validateEmailExists($user->getId(), $user->getUsername(), 'username', User::USER_EXISTING_NAME_AS_EMAIL, $context);
|
||||
}
|
||||
|
||||
if ($user->getUsername() !== null) {
|
||||
$existingByName = $this->userService->findUserByName($user->getUsername());
|
||||
$this->validateUsernameExists($user->getId(), $user->getUsername(), 'username', User::USER_EXISTING_NAME, $context);
|
||||
$this->validateUsernameExists($user->getId(), $user->getEmail(), 'email', User::USER_EXISTING_EMAIL_AS_NAME, $context);
|
||||
}
|
||||
}
|
||||
|
||||
if (null !== $existingByName && $user->getId() !== $existingByName->getId()) {
|
||||
$context->buildViolation(User::getErrorName(User::USER_EXISTING_NAME))
|
||||
->atPath('username')
|
||||
->setTranslationDomain('validators')
|
||||
->setCode(User::USER_EXISTING_NAME)
|
||||
->addViolation();
|
||||
}
|
||||
private function validateEmailExists(?int $userId, string $email, string $path, string $code, ExecutionContextInterface $context): void
|
||||
{
|
||||
$existingByEmail = $this->userService->findUserByEmail($email);
|
||||
|
||||
if (null !== $existingByEmail && $userId !== $existingByEmail->getId()) {
|
||||
$context->buildViolation(User::getErrorName($code))
|
||||
->atPath($path)
|
||||
->setTranslationDomain('validators')
|
||||
->setCode($code)
|
||||
->addViolation();
|
||||
}
|
||||
}
|
||||
|
||||
private function validateUsernameExists(?int $userId, string $username, string $path, string $code, ExecutionContextInterface $context): void
|
||||
{
|
||||
$existingByName = $this->userService->findUserByName($username);
|
||||
|
||||
if (null !== $existingByName && $userId !== $existingByName->getId()) {
|
||||
$context->buildViolation(User::getErrorName($code))
|
||||
->atPath($path)
|
||||
->setTranslationDomain('validators')
|
||||
->setCode($code)
|
||||
->addViolation();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user