You are here

public function CommentNameConstraintValidator::validate in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/comment/src/Plugin/Validation/Constraint/CommentNameConstraintValidator.php \Drupal\comment\Plugin\Validation\Constraint\CommentNameConstraintValidator::validate()

Checks if the passed value is valid.

Parameters

mixed $value The value that should be validated:

Constraint $constraint The constraint for the validation:

Overrides ConstraintValidatorInterface::validate

File

core/modules/comment/src/Plugin/Validation/Constraint/CommentNameConstraintValidator.php, line 56
Contains \Drupal\comment\Plugin\Validation\Constraint\CommentNameConstraintValidator.

Class

CommentNameConstraintValidator
Validates the CommentName constraint.

Namespace

Drupal\comment\Plugin\Validation\Constraint

Code

public function validate($entity, Constraint $constraint) {
  $author_name = $entity->name->value;
  $owner_id = (int) $entity->uid->target_id;

  // Do not allow unauthenticated comment authors to use a name that is
  // taken by a registered user.
  if (isset($author_name) && $author_name !== '' && $owner_id === 0) {
    $users = $this->userStorage
      ->loadByProperties(array(
      'name' => $author_name,
    ));
    if (!empty($users)) {
      $this->context
        ->buildViolation($constraint->messageNameTaken, array(
        '%name' => $author_name,
      ))
        ->atPath('name')
        ->addViolation();
    }
  }
  elseif (isset($author_name) && $author_name !== '' && $owner_id) {
    $owner = $this->userStorage
      ->load($owner_id);
    if ($owner
      ->getUsername() != $author_name) {
      $this->context
        ->buildViolation($constraint->messageMatch)
        ->atPath('name')
        ->addViolation();
    }
  }

  // Anonymous account might be required - depending on field settings.
  if ($owner_id === 0 && empty($author_name) && $this
    ->getAnonymousContactDetailsSetting($entity) === COMMENT_ANONYMOUS_MUST_CONTACT) {
    $this->context
      ->buildViolation($constraint->messageRequired)
      ->atPath('name')
      ->addViolation();
  }
}