Version 1
[yaffs-website] / web / core / modules / user / src / Plugin / Validation / Constraint / UserMailRequiredValidator.php
diff --git a/web/core/modules/user/src/Plugin/Validation/Constraint/UserMailRequiredValidator.php b/web/core/modules/user/src/Plugin/Validation/Constraint/UserMailRequiredValidator.php
new file mode 100644 (file)
index 0000000..7e20b7a
--- /dev/null
@@ -0,0 +1,39 @@
+<?php
+
+namespace Drupal\user\Plugin\Validation\Constraint;
+
+use Symfony\Component\Validator\ConstraintValidator;
+use Symfony\Component\Validator\Constraint;
+
+/**
+ * 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.
+ */
+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();
+    $existing_value = NULL;
+    if ($account->id()) {
+      $account_unchanged = \Drupal::entityManager()
+        ->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()]);
+    }
+  }
+
+}