You are here

function email_confirmer_user_email_confirmer in Email confirmer 8

Implements hook_email_confirmer().

File

email_confirmer_user/email_confirmer_user.module, line 77
Users related email confirmation module.

Code

function email_confirmer_user_email_confirmer($op, EmailConfirmationInterface $confirmation) {

  /** @var \Drupal\user\UserInterface $user */
  if ($confirmation
    ->getRealm() == 'email_confirmer_user' && ($config = \Drupal::config('email_confirmer_user.settings')
    ->get('user_email_change')) && $config['enabled'] && ($user_id = $confirmation
    ->getProperty('user')) && ($new_email = \Drupal::service('user.data')
    ->get('email_confirmer_user', $user_id, 'email_change_new_address')) && $new_email == $confirmation
    ->getEmail() && ($user = \Drupal::entityTypeManager()
    ->getStorage('user')
    ->load($user_id))) {

    // Delete the requested new email from user data.
    \Drupal::service('user.data')
      ->delete('email_confirmer_user', $user_id, 'email_change_new_address');
    switch ($op) {
      case 'confirm':

        // User's email address must be unique on the site.
        if (user_load_by_mail($new_email)) {
          \Drupal::messenger()
            ->addError(t('The email address %value is already taken.', [
            '%value' => $new_email,
          ]));
          break;
        }
        $user
          ->setEmail($new_email);

        // Prevents from cycling email change confirmation.
        drupal_static('email_confirmer_user_' . $user_id, TRUE);
        $user
          ->save();
        \Drupal::messenger()
          ->addStatus(\Drupal::currentUser()
          ->id() == $user_id ? t('Your email address has been updated to %mail', [
          '%mail' => $new_email,
        ]) : t("%user's email address has been updated to %mail", [
          '%user' => $user
            ->getDisplayName(),
          '%mail' => $new_email,
        ]));
        break;
      case 'cancel':
        \Drupal::logger('email_confirmer_user')
          ->warning('Requested user email change for %user has been rejected by the %mail email address owner.', [
          '%user' => $user
            ->getDisplayName(),
          '%mail' => $new_email,
        ]);
        break;
    }
  }
}