You are here

public function BookAccessHelper::setDefaultForRole in Book access 1.x

Set defaults for newly created roles.

See hook_ENTITY_TYPE_create() in book.module.

Parameters

\Drupal\user\RoleInterface $role: The role to set the default for.

Based on the role name, this initializes the default grants for the role id. This is only intended to be used during hook_init() or when creating a brand new role.

1 call to BookAccessHelper::setDefaultForRole()
BookAccessHelper::getRoleBookAccessDefaults in src/BookAccessHelper.php
Get the saved defaults for every role sorted by role weight.

File

src/BookAccessHelper.php, line 115

Class

BookAccessHelper
Helper functions for book_access.

Namespace

Drupal\book_access

Code

public function setDefaultForRole(RoleInterface $role) {
  $role_id = $role
    ->id();
  if ($role_id == 'administrator') {
    $defaultToUse = $this
      ->defaultGrants('administrator');
  }
  elseif ($role_id == '__author__') {
    $this->logger
      ->error($this
      ->t("Could not set default book_access grants for role: @rid", [
      '@rid' => $role_id,
    ]));
    return;
  }
  else {
    $defaultToUse = $this
      ->defaultGrants($role_id);
  }
  $values = [
    'id' => $role_id,
    'label' => $this
      ->t('%role_label role default grants', [
      '%role_label' => $role
        ->label(),
    ]),
    'grant_type' => 'role',
    'role_id' => $role_id,
    'grants' => $defaultToUse,
  ];
  try {
    $this->entityTypeManager
      ->getStorage('book_access_defaults')
      ->create($values)
      ->save();
  } catch (InvalidPluginDefinitionException $e) {
    $this->logger
      ->error($this
      ->t("Could not set default book_access grants for role: @rid", [
      '@rid' => $role_id,
    ]));
  } catch (PluginNotFoundException $e) {
    $this->logger
      ->error($this
      ->t("Could not set default book_access grants for role: @rid", [
      '@rid' => $role_id,
    ]));
  } catch (EntityStorageException $e) {
    $this->logger
      ->error($this
      ->t("Could not set default book_access grants for role: @rid", [
      '@rid' => $role_id,
    ]));
  }
}