You are here

protected function BrowserTestBase::drupalCreateRole in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/simpletest/src/BrowserTestBase.php \Drupal\simpletest\BrowserTestBase::drupalCreateRole()

Creates a role with specified permissions.

Parameters

array $permissions: Array of permission names to assign to role.

string $rid: (optional) The role ID (machine name). Defaults to a random name.

string $name: (optional) The label for the role. Defaults to a random string.

int $weight: (optional) The weight for the role. Defaults NULL so that entity_create() sets the weight to maximum + 1.

Return value

string Role ID of newly created role, or FALSE if role creation failed.

1 call to BrowserTestBase::drupalCreateRole()
BrowserTestBase::drupalCreateUser in core/modules/simpletest/src/BrowserTestBase.php
Creates a user with a given set of permissions.

File

core/modules/simpletest/src/BrowserTestBase.php, line 590
Contains \Drupal\simpletest\BrowserTestBase.

Class

BrowserTestBase
Provides a test case for functional Drupal tests.

Namespace

Drupal\simpletest

Code

protected function drupalCreateRole(array $permissions, $rid = NULL, $name = NULL, $weight = NULL) {

  // Generate a random, lowercase machine name if none was passed.
  if (!isset($rid)) {
    $rid = strtolower($this
      ->randomMachineName(8));
  }

  // Generate a random label.
  if (!isset($name)) {

    // In the role UI role names are trimmed and random string can start or
    // end with a space.
    $name = trim($this
      ->randomString(8));
  }

  // Check the all the permissions strings are valid.
  if (!$this
    ->checkPermissions($permissions)) {
    return FALSE;
  }

  // Create new role.

  /* @var \Drupal\user\RoleInterface $role */
  $role = entity_create('user_role', array(
    'id' => $rid,
    'label' => $name,
  ));
  if (!is_null($weight)) {
    $role
      ->set('weight', $weight);
  }
  $result = $role
    ->save();
  $this
    ->assertSame($result, SAVED_NEW, SafeMarkup::format('Created role ID @rid with name @name.', array(
    '@name' => var_export($role
      ->label(), TRUE),
    '@rid' => var_export($role
      ->id(), TRUE),
  )));
  if ($result === SAVED_NEW) {

    // Grant the specified permissions to the role, if any.
    if (!empty($permissions)) {
      user_role_grant_permissions($role
        ->id(), $permissions);
      $assigned_permissions = entity_load('user_role', $role
        ->id())
        ->getPermissions();
      $missing_permissions = array_diff($permissions, $assigned_permissions);
      if ($missing_permissions) {
        $this
          ->fail(SafeMarkup::format('Failed to create permissions: @perms', array(
          '@perms' => implode(', ', $missing_permissions),
        )));
      }
    }
    return $role
      ->id();
  }
  return FALSE;
}