hasRole example


function hook_entity_form_mode_alter(&$form_mode, \Drupal\Core\Entity\EntityInterface $entity) {
  // Change the form mode for users with Administrator role.   if ($entity->getEntityTypeId() == 'user' && $entity->hasRole('administrator')) {
    $form_mode = 'my_custom_form_mode';
  }
}

/** * Alter the settings used for displaying an entity form. * * @param \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display * The entity_form_display object that will be used to display the entity form * components. * @param array $context * An associative array containing: * - entity_type: The entity type, e.g., 'node' or 'user'. * - bundle: The bundle, e.g., 'page' or 'article'. * - form_mode: The form mode; e.g., 'default', 'profile', 'register', etc. * * @ingroup entity_crud */

    $this->drupalGet('test-user-bulk-form');
    $this->submitForm($edit, 'Apply to selected items');
    $this->assertSession()->pageTextContains('No users selected.');

    // Assign a role to a user.     $account = $user_storage->load($this->users[0]->id());
    $roles = user_role_names(TRUE);
    unset($roles[RoleInterface::AUTHENTICATED_ID]);
    $role = key($roles);

    $this->assertFalse($account->hasRole($role), 'The user currently does not have a custom role.');
    $edit = [
      'user_bulk_form[1]' => TRUE,
      'action' => 'user_add_role_action.' . $role,
    ];
    $this->submitForm($edit, 'Apply to selected items');
    // Re-load the user and check their roles.     $user_storage->resetCache([$account->id()]);
    $account = $user_storage->load($account->id());
    $this->assertTrue($account->hasRole($role), 'The user now has the custom role.');

    $edit = [
      
// 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'));
    

class RemoveRoleUser extends ChangeUserRoleBase {

  /** * {@inheritdoc} */
  public function execute($account = NULL) {
    $rid = $this->configuration['rid'];
    // Skip removing the role from the user if they already don't have it.     if ($account !== FALSE && $account->hasRole($rid)) {
      // For efficiency manually save the original account before applying       // any changes.       $account->original = clone $account;
      $account->removeRole($rid);
      $account->save();
    }
  }

}

class AddRoleUser extends ChangeUserRoleBase {

  /** * {@inheritdoc} */
  public function execute($account = NULL) {
    $rid = $this->configuration['rid'];
    // Skip adding the role to the user if they already have it.     if ($account !== FALSE && !$account->hasRole($rid)) {
      // For efficiency manually save the original account before applying       // any changes.       $account->original = clone $account;
      $account->addRole($rid);
      $account->save();
    }
  }

}
public function initAclRoles()
    {
        $repository = $this->em->getRepository(Role::class);
        $roles = $repository->findAll();

        /** @var Role $role */
        foreach ($roles as $role) {
            /** @var Role|null $parent */
            $parent = $role->getParent();

            // Parent exist and not already added?             if ($parent && !$this->hasRole($parent)) {
                // Register role and register role privileges                 $this->addRole($parent);
            }

            // If parent exists, the pass the parent name to the addRole function             $this->addRole($role$parent);
        }

        return $this;
    }

    
public function testUserGetRoles() {
    $this->assertEquals([RoleInterface::AUTHENTICATED_ID, 'role_two']$this->users['user_three']->getRoles());
    $this->assertEquals(['role_two']$this->users['user_three']->getRoles(TRUE));
  }

  /** * Tests the hasRole method. * * @covers ::hasRole */
  public function testHasRole() {
    $this->assertTrue($this->users['user_one']->hasRole('role_one'));
    $this->assertFalse($this->users['user_two']->hasRole('no role'));
    $this->assertTrue($this->users['user_three']->hasRole(RoleInterface::AUTHENTICATED_ID));
    $this->assertFalse($this->users['user_three']->hasRole(RoleInterface::ANONYMOUS_ID));
    $this->assertTrue($this->users['user_last']->hasRole(RoleInterface::ANONYMOUS_ID));
  }

}

  public function hasRole(string $rid): bool {
    return $this->getAccount()->hasRole($rid);
  }

  /** * {@inheritdoc} */
  public function hasPermission($permission) {
    return $this->getAccount()->hasPermission($permission);
  }

  /** * {@inheritdoc} */
$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();
    $role_storage->create(['id' => 'test_role_three', 'label' => 'Test role 3'])->save();

    $values = [
      'uid' => 1,
      'roles' => ['test_role_one'],
    ];
    $user = User::create($values);

    $this->assertTrue($user->hasRole('test_role_one'));
    $this->assertFalse($user->hasRole('test_role_two'));
    $this->assertEquals([RoleInterface::AUTHENTICATED_ID, 'test_role_one']$user->getRoles());

    $account = $user->addRole('test_role_one');
    $this->assertSame($user$account);
    $this->assertTrue($user->hasRole('test_role_one'));
    $this->assertFalse($user->hasRole('test_role_two'));
    $this->assertEquals([RoleInterface::AUTHENTICATED_ID, 'test_role_one']$user->getRoles());

    $user->addRole('test_role_two');
    $this->assertTrue($user->hasRole('test_role_one'));
    
$account_proxy->setAccount($current_user->reveal());
    $account_proxy->setInitialAccountId(1);
  }

  /** * @covers ::hasRole */
  public function testHasRole() {
    $dispatcher = $this->prophesize(EventDispatcherInterface::class);
    $dispatcher->dispatch(Argument::any(), Argument::any())->willReturn(new Event());
    $account_proxy = new AccountProxy($dispatcher->reveal());
    $this->assertTrue($account_proxy->hasRole(RoleInterface::ANONYMOUS_ID));

    $current_user = $this->prophesize(UserSession::class);
    $current_user->id()->willReturn(2);
    $current_user->hasRole(RoleInterface::AUTHENTICATED_ID)->willReturn(TRUE);
    $account_proxy->setAccount($current_user->reveal());
    $this->assertTrue($account_proxy->hasRole(RoleInterface::AUTHENTICATED_ID));
  }

}
Home | Imprint | This part of the site doesn't use cookies.