You are here

protected function UserManager::generateUniqueUsername in Social Auth 8.2

Same name and namespace in other branches
  1. 3.x src/User/UserManager.php \Drupal\social_auth\User\UserManager::generateUniqueUsername()

Ensures that Drupal usernames will be unique.

Drupal usernames will be generated so that the user's full name on provider will become user's Drupal username. This method will check if the username is already used and appends a number until it finds the first available username.

Parameters

string $name: User's full name on provider.

Return value

string Unique drupal username.

1 call to UserManager::generateUniqueUsername()
UserManager::getUserFields in src/User/UserManager.php
Returns an array of fields to initialize the creation of the user.

File

src/User/UserManager.php, line 458

Class

UserManager
Manages database related tasks.

Namespace

Drupal\social_auth\User

Code

protected function generateUniqueUsername($name) {
  $max_length = 60;
  $name = mb_substr($name, 0, $max_length);
  $name = str_replace(' ', '', $name);
  $name = strtolower($name);

  // Add a trailing number if needed to make username unique.
  $base = $name;
  $i = 1;
  $candidate = $base;
  while ($this
    ->loadUserByProperty('name', $candidate)) {

    // Calculate max length for $base and truncate if needed.
    $max_length_base = $max_length - strlen((string) $i) - 1;
    $base = mb_substr($base, 0, $max_length_base);
    $candidate = $base . $i;
    $i++;
  }

  // Trim leading and trailing whitespace.
  $candidate = trim($candidate);
  return $candidate;
}