function UserRoleDeleteTest::testRoleDeleteUserRoleReferenceDelete

Same name in other branches
  1. 9 core/modules/user/tests/src/Kernel/UserRoleDeleteTest.php \Drupal\Tests\user\Kernel\UserRoleDeleteTest::testRoleDeleteUserRoleReferenceDelete()
  2. 8.9.x core/modules/user/tests/src/Kernel/UserRoleDeleteTest.php \Drupal\Tests\user\Kernel\UserRoleDeleteTest::testRoleDeleteUserRoleReferenceDelete()
  3. 10 core/modules/user/tests/src/Kernel/UserRoleDeleteTest.php \Drupal\Tests\user\Kernel\UserRoleDeleteTest::testRoleDeleteUserRoleReferenceDelete()

Tests removal of role references on role entity delete.

See also

user_user_role_delete()

File

core/modules/user/tests/src/Kernel/UserRoleDeleteTest.php, line 38

Class

UserRoleDeleteTest
Tests the handling of user_role entity from the user module.

Namespace

Drupal\Tests\user\Kernel

Code

public function testRoleDeleteUserRoleReferenceDelete() : void {
    // Create two test roles.
    $role_storage = $this->container
        ->get('entity_type.manager')
        ->getStorage('user_role');
    $role_storage->create([
        'id' => 'test_role_one',
        'label' => 'Test role 1',
    ])
        ->save();
    $role_storage->create([
        'id' => 'test_role_two',
        'label' => 'Test role 2',
    ])
        ->save();
    // Create user and assign both test roles.
    $values = [
        'uid' => 1,
        'name' => $this->randomString(),
        'roles' => [
            'test_role_one',
            'test_role_two',
        ],
    ];
    $user = User::create($values);
    $user->save();
    // Check that user has both roles.
    $this->assertTrue($user->hasRole('test_role_one'));
    $this->assertTrue($user->hasRole('test_role_two'));
    // Delete test role one.
    $test_role_one = $role_storage->load('test_role_one');
    $test_role_one->delete();
    // Load user again from the database.
    $user = User::load($user->id());
    // Check that user does not have role one anymore, still has role two.
    $this->assertFalse($user->hasRole('test_role_one'));
    $this->assertTrue($user->hasRole('test_role_two'));
    // Create new role with same name.
    $role_storage->create([
        'id' => 'test_role_one',
        'label' => 'Test role 1',
    ])
        ->save();
    // Load user again from the database.
    $user = User::load($user->id());
    // Check that user does not have role one.
    $this->assertFalse($user->hasRole('test_role_one'));
    $this->assertTrue($user->hasRole('test_role_two'));
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.