You are here

class UserMailRequiredValidator in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/user/src/Plugin/Validation/Constraint/UserMailRequiredValidator.php \Drupal\user\Plugin\Validation\Constraint\UserMailRequiredValidator

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

The user mail field is NOT required if account originally had no mail set and the user performing the edit has 'administer users' permission. This allows users without email address to be edited and deleted.

Hierarchy

  • class \Drupal\user\Plugin\Validation\Constraint\UserMailRequiredValidator extends \Symfony\Component\Validator\ConstraintValidator

Expanded class hierarchy of UserMailRequiredValidator

1 file declares its use of UserMailRequiredValidator
UserMailRequiredValidatorTest.php in core/modules/user/tests/src/Unit/Plugin/Validation/Constraint/UserMailRequiredValidatorTest.php

File

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

Namespace

Drupal\user\Plugin\Validation\Constraint
View source
class UserMailRequiredValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  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(),
      ]);
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
UserMailRequiredValidator::validate public function Checks if the passed value is valid.