You are here

protected function UserCreationTrait::setUpCurrentUser in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/user/tests/src/Traits/UserCreationTrait.php \Drupal\Tests\user\Traits\UserCreationTrait::setUpCurrentUser()
  2. 10 core/modules/user/tests/src/Traits/UserCreationTrait.php \Drupal\Tests\user\Traits\UserCreationTrait::setUpCurrentUser()

Creates a random user account and sets it as current user.

Unless explicitly specified by setting the user ID to 1, a regular user account will be created and set as current, after creating user account 1. Additionally, this will ensure that at least the anonymous user account exists regardless of the specified user ID.

Parameters

array $values: (optional) An array of initial user field values.

array $permissions: (optional) Array of permission names to assign to user. Note that the user always has the default permissions derived from the "authenticated users" role.

bool $admin: (optional) Whether the user should be an administrator with all the available permissions.

Return value

\Drupal\user\UserInterface A user account object.

Throws

\LogicException If attempting to assign additional roles to the anonymous user account.

\Drupal\Core\Entity\EntityStorageException If the user could not be saved.

23 calls to UserCreationTrait::setUpCurrentUser()
ActiveWorkspaceUpdateTest::setUp in core/modules/workspaces/tests/src/Functional/UpdateSystem/ActiveWorkspaceUpdateTest.php
EntityConverterLatestRevisionTest::setUp in core/tests/Drupal/KernelTests/Core/ParamConverter/EntityConverterLatestRevisionTest.php
EntityConverterTest::setUp in core/tests/Drupal/KernelTests/Core/ParamConverter/EntityConverterTest.php
EntityRepositoryTest::setUp in core/tests/Drupal/KernelTests/Core/Entity/EntityRepositoryTest.php
FieldEntityLinkTest::setUpFixtures in core/modules/views/tests/src/Kernel/Handler/FieldEntityLinkTest.php
Sets up the configuration and schema of views and views_test_data modules.

... See full list

File

core/modules/user/tests/src/Traits/UserCreationTrait.php, line 49

Class

UserCreationTrait
Provides methods to create additional test users and switch the currently logged in one.

Namespace

Drupal\Tests\user\Traits

Code

protected function setUpCurrentUser(array $values = [], array $permissions = [], $admin = FALSE) {
  $values += [
    'name' => $this
      ->randomMachineName(),
  ];

  // In many cases the anonymous user account is fine for testing purposes,
  // however, if we need to create a user with a non-empty ID, we need also
  // the "sequences" table.
  if (!\Drupal::moduleHandler()
    ->moduleExists('system')) {
    $values['uid'] = 0;
  }
  if ($this instanceof KernelTestBase && (!isset($values['uid']) || $values['uid'])) {
    try {
      $this
        ->installSchema('system', [
        'sequences',
      ]);
    } catch (SchemaObjectExistsException $e) {
    }
  }

  // Creating an administrator or assigning custom permissions would result in
  // creating and assigning a new role to the user. This is not possible with
  // the anonymous user account.
  if (($admin || $permissions) && isset($values['uid']) && is_numeric($values['uid']) && $values['uid'] == 0) {
    throw new \LogicException('The anonymous user account cannot have additional roles.');
  }
  $original_permissions = $permissions;
  $original_admin = $admin;
  $original_values = $values;
  $autocreate_user_1 = !isset($values['uid']) || $values['uid'] > 1;

  // No need to create user account 1 if it already exists.
  try {
    $autocreate_user_1 = $autocreate_user_1 && !User::load(1);
  } catch (DatabaseExceptionWrapper $e) {

    // Missing schema, it will be created later on.
  }

  // Save the user entity object and created its schema if needed.
  try {
    if ($autocreate_user_1) {
      $permissions = [];
      $admin = FALSE;
      $values = [];
    }
    $user = $this
      ->createUser($permissions, NULL, $admin, $values);
  } catch (EntityStorageException $e) {
    if ($this instanceof KernelTestBase) {
      $this
        ->installEntitySchema('user');
      $user = $this
        ->createUser($permissions, NULL, $admin, $values);
    }
    else {
      throw $e;
    }
  }

  // Ensure the anonymous user account exists.
  if (!User::load(0)) {
    $values = [
      'uid' => 0,
      'status' => 0,
      'name' => '',
    ];
    User::create($values)
      ->save();
  }

  // If we automatically created user account 1, we need to create a regular
  // user account before setting up the current user service to avoid
  // potential false positives caused by access control bypass.
  if ($autocreate_user_1) {
    $user = $this
      ->createUser($original_permissions, NULL, $original_admin, $original_values);
  }
  $this
    ->setCurrentUser($user);
  return $user;
}