You are here

public function ProtectedUserFieldConstraintValidator::validate in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/user/src/Plugin/Validation/Constraint/ProtectedUserFieldConstraintValidator.php \Drupal\user\Plugin\Validation\Constraint\ProtectedUserFieldConstraintValidator::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/user/src/Plugin/Validation/Constraint/ProtectedUserFieldConstraintValidator.php, line 61
Contains \Drupal\user\Plugin\Validation\Constraint\ProtectedUserFieldConstraintValidator.

Class

ProtectedUserFieldConstraintValidator
Validates the ProtectedUserFieldConstraint constraint.

Namespace

Drupal\user\Plugin\Validation\Constraint

Code

public function validate($items, Constraint $constraint) {
  if (!isset($items)) {
    return;
  }

  /* @var \Drupal\Core\Field\FieldItemListInterface $items */
  $field = $items
    ->getFieldDefinition();

  /* @var \Drupal\user\UserInterface $account */
  $account = $items
    ->getEntity();
  if (!isset($account) || !empty($account->_skipProtectedUserFieldConstraint)) {

    // Looks like we are validating a field not being part of a user, or the
    // constraint should be skipped, so do nothing.
    return;
  }

  // Only validate for existing entities and if this is the current user.
  if (!$account
    ->isNew() && $account
    ->id() == $this->currentUser
    ->id()) {

    /* @var \Drupal\user\UserInterface $account_unchanged */
    $account_unchanged = $this->userStorage
      ->loadUnchanged($account
      ->id());
    $changed = FALSE;

    // Special case for the password, it being empty means that the existing
    // password should not be changed, ignore empty password fields.
    $value = $items->value;
    if ($field
      ->getName() != 'pass' || !empty($value)) {

      // Compare the values of the field this is being validated on.
      $changed = $items
        ->getValue() != $account_unchanged
        ->get($field
        ->getName())
        ->getValue();
    }
    if ($changed && !$account
      ->checkExistingPassword($account_unchanged)) {
      $this->context
        ->addViolation($constraint->message, array(
        '%name' => $field
          ->getLabel(),
      ));
    }
  }
}