user_api-1.0.0-beta1/modules/user_api_email_confirm/src/EmailValidationTrait.php

modules/user_api_email_confirm/src/EmailValidationTrait.php
<?php

declare(strict_types=1);

namespace Drupal\user_api_email_confirm;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\user_api\ErrorCode;
use Symfony\Component\HttpFoundation\Response;
use Wunderwerk\JsonApiError\JsonApiErrorResponse;

/**
 * Trait for email validation.
 */
trait EmailValidationTrait {

  /**
   * The current user.
   */
  protected AccountProxyInterface $currentUser;

  /**
   * The entity type manager.
   */
  protected EntityTypeManagerInterface $entityTypeManager;

  /**
   * Validate email address.
   *
   * Checks if the email is safe to be used.
   *
   * @return \Symfony\Component\HttpFoundation\Response|null
   *   The error response if validation fails.
   */
  protected function validateEmail(string $mail): ?Response {
    // Check if the email address is valid.
    if ($mail === $this->currentUser->getEmail()) {
      return JsonApiErrorResponse::fromError(
        status: 422,
        code: ErrorCode::EmailSameAsCurrent->getCode(),
        title: 'Email same as current.',
        detail: 'The new email address is the same as the current email address.',
      );
    }

    // Check if the email address already exists.
    if ($this->doesEmailExist($mail)) {
      return JsonApiErrorResponse::fromError(
        status: 422,
        code: ErrorCode::EmailAlreadyExists->getCode(),
        title: 'Email already exists.',
        detail: 'The new email address is already in use.',
      );
    }

    return NULL;
  }

  /**
   * Checks if the email address already exists.
   */
  protected function doesEmailExist(string $mail): bool {
    $query = $this->entityTypeManager->getStorage('user')->getQuery()
      ->accessCheck(FALSE)
      ->condition('mail', $mail)
      ->count();

    return $query->execute() > 0;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc