3 namespace Drupal\user\Entity;
5 use Drupal\Core\Config\Entity\ConfigEntityBase;
6 use Drupal\Core\Entity\EntityStorageInterface;
7 use Drupal\user\RoleInterface;
10 * Defines the user role entity class.
14 * label = @Translation("Role"),
16 * "storage" = "Drupal\user\RoleStorage",
17 * "access" = "Drupal\user\RoleAccessControlHandler",
18 * "list_builder" = "Drupal\user\RoleListBuilder",
20 * "default" = "Drupal\user\RoleForm",
21 * "delete" = "Drupal\Core\Entity\EntityDeleteForm"
24 * admin_permission = "administer permissions",
25 * config_prefix = "role",
26 * static_cache = TRUE,
29 * "weight" = "weight",
33 * "delete-form" = "/admin/people/roles/manage/{user_role}/delete",
34 * "edit-form" = "/admin/people/roles/manage/{user_role}",
35 * "edit-permissions-form" = "/admin/people/permissions/{user_role}",
36 * "collection" = "/admin/people/roles",
47 class Role extends ConfigEntityBase implements RoleInterface {
50 * The machine name of this role.
57 * The human-readable label of this role.
64 * The weight of this role in administrative listings.
71 * The permissions belonging to this role.
75 protected $permissions = [];
78 * An indicator whether the role has all permissions.
87 public function getPermissions() {
88 if ($this->isAdmin()) {
91 return $this->permissions;
97 public function getWeight() {
98 return $this->get('weight');
104 public function setWeight($weight) {
105 $this->set('weight', $weight);
112 public function hasPermission($permission) {
113 if ($this->isAdmin()) {
116 return in_array($permission, $this->permissions);
122 public function grantPermission($permission) {
123 if ($this->isAdmin()) {
126 if (!$this->hasPermission($permission)) {
127 $this->permissions[] = $permission;
135 public function revokePermission($permission) {
136 if ($this->isAdmin()) {
139 $this->permissions = array_diff($this->permissions, [$permission]);
146 public function isAdmin() {
147 return (bool) $this->is_admin;
153 public function setIsAdmin($is_admin) {
154 $this->is_admin = $is_admin;
161 public static function postLoad(EntityStorageInterface $storage, array &$entities) {
162 parent::postLoad($storage, $entities);
163 // Sort the queried roles by their weight.
164 // See \Drupal\Core\Config\Entity\ConfigEntityBase::sort().
165 uasort($entities, 'static::sort');
171 public function preSave(EntityStorageInterface $storage) {
172 parent::preSave($storage);
174 if (!isset($this->weight) && ($roles = $storage->loadMultiple())) {
175 // Set a role weight to make this new role last.
176 $max = array_reduce($roles, function ($max, $role) {
177 return $max > $role->weight ? $max : $role->weight;
179 $this->weight = $max + 1;
182 if (!$this->isSyncing()) {
183 // Permissions are always ordered alphabetically to avoid conflicts in the
184 // exported configuration.
185 sort($this->permissions);