You are here

protected function SocialAuthUserManager::generateUniqueUsername in Social Auth 8

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 SocialAuthUserManager::generateUniqueUsername()
SocialAuthUserManager::getUserFields in src/SocialAuthUserManager.php
Returns an array of fields to initialize the creation of the user.

File

src/SocialAuthUserManager.php, line 505

Class

SocialAuthUserManager
Contains all logic that is related to Drupal user management.

Namespace

Drupal\social_auth

Code

protected function generateUniqueUsername($name) {
  $max_length = 60;
  $name = Unicode::substr($name, 0, $max_length);

  // 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 = Unicode::substr($base, 0, $max_length_base);
    $candidate = $base . ' ' . $i;
    $i++;
  }

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