You are here

function email_registration_user_insert in Email Registration 8

Same name and namespace in other branches
  1. 7 email_registration.module \email_registration_user_insert()

Implements hook_ENTITY_TYPE_insert().

Alter the user name (after entity being stored).

File

./email_registration.module, line 18
Allows users to register with an email address as their username.

Code

function email_registration_user_insert(UserInterface $account) {

  // Don't create a new username if one is already set.
  $name = $account
    ->getAccountName();
  if (!empty($name) && strpos($name, 'email_registration_') !== 0) {
    return;
  }

  // Other modules may implement hook_email_registration_name($edit, $account)
  // to generate a username (return a string to be used as the username, NULL
  // to have email_registration generate it).
  $names = Drupal::moduleHandler()
    ->invokeAll('email_registration_name', [
    $account,
  ]);

  // Remove any empty entries.
  $names = array_filter($names);
  if (empty($names)) {

    // Strip off everything after the @ sign.
    $new_name = preg_replace('/@.*$/', '', $account
      ->getEmail());

    // Clean up the username.
    $new_name = email_registration_cleanup_username($new_name);
  }
  else {

    // One would expect a single implementation of the hook, but if there
    // are multiples out there use the last one.
    $new_name = array_pop($names);
  }

  // Ensure whatever name we have is unique.
  $new_name = email_registration_unique_username($new_name, (int) $account
    ->id());
  $account
    ->setUsername($new_name);
  if ($account
    ->isValidationRequired() && !$account
    ->validate()) {
    \Drupal::logger('email_registration')
      ->error('Email registration failed setting the new name on user @id.', [
      '@id' => $account
        ->id(),
    ]);
    return;
  }
  $account
    ->save();
}