Implement 'callable'-version of RIP for hook_update

Created on 1 October 2024, 5 months ago

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();
}
Feature request
Status

Active

Version

1.1

Component

Code

Created by

🇳🇱Netherlands koosvdkolk

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @koosvdkolk
  • Status changed to Postponed: needs info 3 months ago
  • 🇩🇪Germany simonbaese Berlin

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

  • 🇳🇱Netherlands koosvdkolk

    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.

  • 🇩🇪Germany simonbaese Berlin

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

Production build 0.71.5 2024