function UserMailRequiredValidator::validate

Same name in other branches
  1. 9 core/modules/user/src/Plugin/Validation/Constraint/UserMailRequiredValidator.php \Drupal\user\Plugin\Validation\Constraint\UserMailRequiredValidator::validate()
  2. 8.9.x core/modules/user/src/Plugin/Validation/Constraint/UserMailRequiredValidator.php \Drupal\user\Plugin\Validation\Constraint\UserMailRequiredValidator::validate()
  3. 11.x core/modules/user/src/Plugin/Validation/Constraint/UserMailRequiredValidator.php \Drupal\user\Plugin\Validation\Constraint\UserMailRequiredValidator::validate()

phpcs:ignore Drupal.Commenting.FunctionComment.VoidReturn

Return value

void

File

core/modules/user/src/Plugin/Validation/Constraint/UserMailRequiredValidator.php, line 23

Class

UserMailRequiredValidator
Checks if the user's email address is provided if required.

Namespace

Drupal\user\Plugin\Validation\Constraint

Code

public function validate($items, Constraint $constraint) {
    
    /** @var \Drupal\Core\Field\FieldItemListInterface $items */
    
    /** @var \Drupal\user\UserInterface $account */
    $account = $items->getEntity();
    if (!isset($account)) {
        return;
    }
    $existing_value = NULL;
    // Only validate for existing user.
    if (!$account->isNew()) {
        $account_unchanged = \Drupal::entityTypeManager()->getStorage('user')
            ->loadUnchanged($account->id());
        $existing_value = $account_unchanged->getEmail();
    }
    $required = !(!$existing_value && \Drupal::currentUser()->hasPermission('administer users'));
    if ($required && (!isset($items) || $items->isEmpty())) {
        $this->context
            ->addViolation($constraint->message, [
            '@name' => $account->getFieldDefinition('mail')
                ->getLabel(),
        ]);
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.