summaryrefslogtreecommitdiffstats
path: root/core/modules/user/lib/Drupal/user/RoleStorageController.php
blob: f5f65758e1c789ecd26e0958e4ac635f8ce15118 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php

/**
 * @file
 * Contains Drupal\user\RoleStorageController.
 */

namespace Drupal\user;

use Drupal\Core\Config\Entity\ConfigStorageController;
use Drupal\Core\Entity\EntityInterface;

/**
 * Controller class for user roles.
 */
class RoleStorageController extends ConfigStorageController {

  /**
   * Overrides ConfigStorageController::preSave().
   */
  public function preSave(EntityInterface $entity) {
    if (!isset($entity->weight) && $roles = entity_load_multiple('user_role')) {
      // Set a role weight to make this new role last.
      $max = array_reduce($roles, function($max, $entity) {
        return $max > $entity->weight ? $max : $entity->weight;
      });
      $entity->weight = $max + 1;
    }
    parent::preSave($entity);
  }

  /**
   * Overrides ConfigStorageController::resetCache().
   */
  public function resetCache(array $ids = NULL) {
    parent::resetCache($ids);

    // Clear the user access cache.
    drupal_static_reset('user_access');
    drupal_static_reset('user_role_permissions');
  }

  /**
   * Overrides ConfigStorageController::postDelete().
   */
  protected function postDelete($entities) {
    $rids = array_keys($entities);

    // Delete permission assignments.
    db_delete('role_permission')
      ->condition('rid', $rids)
      ->execute();
    // Remove the role from all users.
    db_delete('users_roles')
      ->condition('rid', $rids)
      ->execute();
  }

  /**
   * Overrides ConfigStorageController::attachLoad().
   */
  protected function attachLoad(&$queried_entities, $revision_id = FALSE) {
    // Sort the queried roles by their weight.
    uasort($queried_entities, 'Drupal\Core\Config\Entity\ConfigEntityBase::sort');

    parent::attachLoad($queried_entities, $revision_id);
  }

}