You are here

public function SocialAuthUserManager::createUser in Social Auth 8

Create a new user account.

Parameters

string $name: User's name on Provider.

string $email: User's email address.

Return value

\Drupal\user\Entity\User|false Drupal user account if user was created False otherwise

1 call to SocialAuthUserManager::createUser()
SocialAuthUserManager::authenticateUser in src/SocialAuthUserManager.php
Creates and/or authenticates an user.

File

src/SocialAuthUserManager.php, line 285

Class

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

Namespace

Drupal\social_auth

Code

public function createUser($name, $email) {

  // Make sure we have everything we need.
  if (!$name || !$email) {
    $this->loggerFactory
      ->get($this
      ->getPluginId())
      ->error('Failed to create user. Name: @name, email: @email', array(
      '@name' => $name,
      '@email' => $email,
    ));
    return FALSE;
  }

  // Check if site configuration allows new users to register.
  if ($this
    ->registrationBlocked()) {
    $this->loggerFactory
      ->get($this
      ->getPluginId())
      ->warning('Failed to create user. User registration is disabled in Drupal account settings. Name: @name, email: @email.', array(
      '@name' => $name,
      '@email' => $email,
    ));
    drupal_set_message($this
      ->t('User registration is disabled, please contact the administrator.'), 'error');
    return FALSE;
  }

  // Get the current UI language.
  $langcode = $this->languageManager
    ->getCurrentLanguage()
    ->getId();

  // Initializes the user fields.
  $fields = $this
    ->getUserFields($name, $email, $langcode);

  // Create new user account.

  /** @var \Drupal\user\Entity\User $new_user */
  $new_user = $this->entityTypeManager
    ->getStorage('user')
    ->create($fields);

  // Try to save the new user account.
  try {
    $new_user
      ->save();
    $this->loggerFactory
      ->get($this
      ->getPluginId())
      ->notice('New user created. Username @username, UID: @uid', [
      '@username' => $new_user
        ->getAccountName(),
      '@uid' => $new_user
        ->id(),
    ]);

    // Dipatches SocialAuthEvents::USER_CREATED event.
    $event = new SocialAuthUserEvent($new_user, $this
      ->getPluginId());
    $this->eventDispatcher
      ->dispatch(SocialAuthEvents::USER_CREATED, $event);
    return $new_user;
  } catch (EntityStorageException $ex) {
    $this->loggerFactory
      ->get($this
      ->getPluginId())
      ->error('Could not create new user. Exception: @message', [
      '@message' => $ex
        ->getMessage(),
    ]);
  }
  return FALSE;
}