You are here

public function QaAccountsCreateDelete::createQaAccountForRole in QA Accounts 8

Creates QA account for specified role.

Parameters

string $role_name: The machine name of the role the account is to be created for.

Overrides QaAccountsCreateDeleteInterface::createQaAccountForRole

1 call to QaAccountsCreateDelete::createQaAccountForRole()
QaAccountsCreateDelete::createQaAccounts in src/QaAccountsCreateDelete.php
Creates QA accounts for all existing roles.

File

src/QaAccountsCreateDelete.php, line 57

Class

QaAccountsCreateDelete
Service that creates and deletes QA accounts for roles.

Namespace

Drupal\qa_accounts

Code

public function createQaAccountForRole($role_name) {
  $username = 'qa_' . $role_name;

  // Check if qa user already exists.
  $user_storage = $this->entityTypeManager
    ->getStorage('user');
  $uids = $user_storage
    ->getQuery()
    ->condition('name', $username)
    ->accessCheck(FALSE)
    ->range(0, 1)
    ->execute();
  if ($uids) {
    $this->logger
      ->notice('User @name already exists.', [
      '@name' => $username,
    ]);
  }
  else {

    /** @var \Drupal\user\Entity\User $user */
    $user = $user_storage
      ->create();
    $user
      ->enforceIsNew();
    $user
      ->setUsername($username);
    $user
      ->setEmail($username . '@example.com');
    $user
      ->setPassword($username);
    if ($role_name !== 'authenticated') {
      $user
        ->addRole($role_name);
    }
    $user
      ->activate();
    $user
      ->save();
    $this->logger
      ->notice('Created user @name.', [
      '@name' => $username,
    ]);
  }
}