Problem/Motivation

My module has an update making some permissions obsolete. I have ~100 sites. I would like to remove the permissions in a hook_update.

Proposed resolution

Something like this:


namespace Drupal\rip;

/**
 * Class RIPApi
 * Provides helper functions for role and permission management.
 */
class RIPApi {

  /**
   * Static function to remove invalid permissions.
   */
  public static function remove_invalid_permissions() {
    $permission_handler = \Drupal::service('user.permissions');
    $permissions = array_keys($permission_handler->getPermissions());
    $roles = \Drupal::entityTypeManager()
      ->getStorage('user_role')
      ->loadMultiple();
    $removed = FALSE;

    /** @var \Drupal\user\RoleInterface[] $roles */
    foreach ($roles as $role) {
      $role_permissions = $role->getPermissions();
      $diff_permissions_in_role = array_diff($role_permissions, $permissions);

      if ($diff_permissions_in_role) {
        foreach ($diff_permissions_in_role as $permission) {
          \Drupal::logger('rip')
            ->notice('Removed permission: @permission for role: @role', [
              '@permission' => $permission,
              '@role' => $role->id(),
            ]);
          $role->revokePermission($permission);
          $removed = TRUE;
        }
        $role->save();
      }
    }
    if ($removed) {
      \Drupal::logger('rip')->success('Invalid permissions removed.');
    }
    else {
      \Drupal::logger('rip')->success('No permissions to remove.');
    }
  }

}

From my hook_update:

use Drupal\rip\RIPApi;

function my_module_update_10001() {
  RIPApi::remove_invalid_permissions();
}

Comments

koosvdkolk created an issue. See original summary.

simonbaese’s picture

Status: Active » Postponed (maintainer needs more info)

Can you use the batch implementation in RipBatch? I think, that would be more suitable than introducing a static method.

jvdkolk’s picture

Thanks for reaching out!

Can the batch implementation be called from hook_update? For us this is the key part: we want to remove permissions in hook_update.

P.S. We currently just use the OP code and call that, so for us it is not really an issue if you decide to leave RIP as it is.

simonbaese’s picture

Can you please try \Drupal::service('rip.manager')->start(); in your implementation?