You are here

function role_delegation_user_presave in Role Delegation 8

Same name and namespace in other branches
  1. 7 role_delegation.module \role_delegation_user_presave()

Implements hook_ENTITY_TYPE_presave().

File

./role_delegation.module, line 64
Allows admins to grant roles the authority to assign selected roles to users.

Code

function role_delegation_user_presave(UserInterface $entity) {
  if (!$entity
    ->hasField('role_change')) {
    return;
  }
  $submitted_roles = [];
  foreach ($entity->role_change as $item) {
    $submitted_roles[] = $item->target_id;
  }

  // Change roles based on the field for role delegation.
  if ($submitted_roles !== DelegatableRoles::$emptyFieldValue) {
    $current_user = \Drupal::currentUser();
    $delegatable_roles = array_keys(\Drupal::service('delegatable_roles')
      ->getAssignableRoles($current_user));

    // Of the roles that were submitted, only add ones that the user has access
    // to use.
    $add_roles = array_intersect($delegatable_roles, $submitted_roles);
    foreach ($add_roles as $id) {
      $entity
        ->addRole($id);
    }

    // Any roles that the user has access to use and did not include in
    // submission are removals.
    $remove_roles = array_diff($delegatable_roles, $submitted_roles);
    foreach ($remove_roles as $id) {
      $entity
        ->removeRole($id);
    }
  }
}