You are here

public function UserManager::createUser in Social Auth 3.x

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

Create a new user account.

Parameters

\Drupal\social_auth\User\SocialAuthUserInterface $user: The data of the user to be created.

Return value

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

1 call to UserManager::createUser()
UserManager::createNewUser in src/User/UserManager.php
Creates a new user.

File

src/User/UserManager.php, line 164

Class

UserManager
Manages database related tasks.

Namespace

Drupal\social_auth\User

Code

public function createUser(SocialAuthUserInterface $user) {
  $name = $user
    ->getName();
  $email = $user
    ->getEmail();

  // Check if site configuration allows new users to register.
  if ($this
    ->isRegistrationDisabled()) {
    $this->loggerFactory
      ->get($this
      ->getPluginId())
      ->warning('Failed to create user. User registration is disabled. Name: @name, email: @email.', [
      '@name' => $name,
      '@email' => $email,
    ]);
    $this->messenger
      ->addError($this
      ->t('User registration is disabled, please contact the administrator.'));
    return FALSE;
  }

  // Make sure we have everything we need.
  if (!$name) {
    $this->loggerFactory
      ->get($this
      ->getPluginId())
      ->error('Failed to create user. Name: @name', [
      '@name' => $name,
    ]);
    $this->messenger
      ->addError($this
      ->t('You could not be authenticated, please contact the administrator.'));
    return FALSE;
  }

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

  // Try to save the new user account.
  try {

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

    /** @var \Drupal\user\Entity\User $new_user */
    $new_user = $this->entityTypeManager
      ->getStorage('user')
      ->create($fields);
    $new_user
      ->save();
    $this->loggerFactory
      ->get($this
      ->getPluginId())
      ->notice('New user created. Username @username, UID: @uid', [
      '@username' => $new_user
        ->getAccountName(),
      '@uid' => $new_user
        ->id(),
    ]);

    // Dispatches SocialAuthEvents::USER_CREATED event.
    $event = new UserEvent($new_user, $this
      ->getPluginId(), $user);
    $this->eventDispatcher
      ->dispatch(SocialAuthEvents::USER_CREATED, $event);
    return $new_user;
  } catch (\Exception $ex) {
    $this->loggerFactory
      ->get($this
      ->getPluginId())
      ->error('Could not create new user. Exception: @message', [
      '@message' => $ex
        ->getMessage(),
    ]);
  }
  $this->messenger
    ->addError($this
    ->t('You could not be authenticated, please contact the administrator.'));
  return FALSE;
}