diff --git a/core/lib/Drupal/Core/Session/UserSession.php b/core/lib/Drupal/Core/Session/UserSession.php index 704fc79..0e34832 100644 --- a/core/lib/Drupal/Core/Session/UserSession.php +++ b/core/lib/Drupal/Core/Session/UserSession.php @@ -101,6 +101,13 @@ class UserSession implements AccountInterface { protected $hostname = ''; /** + * The role objects the user has. + * + * @var \Drupal\user\Entity\Role[] + */ + protected $loadedRoles; + + /** * Constructs a new user session. * * @param array $values @@ -141,9 +148,7 @@ public function hasPermission($permission) { return TRUE; } - $roles = \Drupal::entityManager()->getStorage('user_role')->loadMultiple($this->getRoles()); - - foreach ($roles as $role) { + foreach ($this->getRolesAsEntities() as $role) { if ($role->hasPermission($permission)) { return TRUE; } @@ -250,4 +255,18 @@ public function getHostname() { return $this->hostname; } + /** + * Gets and loads the roles. + * + * @return \Drupal\user\Entity\Role[] + * The loaded roles. + */ + protected function getRolesAsEntities() { + if (!isset($this->loadedRoles)) { + $this->loadedRoles = \Drupal::entityManager()->getStorageController('user_role')->loadMultiple($this->getRoles()); + } + + return $this->loadedRoles; + } + } diff --git a/core/modules/user/lib/Drupal/user/Entity/User.php b/core/modules/user/lib/Drupal/user/Entity/User.php index fc33baf..a7ecd13 100644 --- a/core/modules/user/lib/Drupal/user/Entity/User.php +++ b/core/modules/user/lib/Drupal/user/Entity/User.php @@ -61,6 +61,13 @@ class User extends ContentEntityBase implements UserInterface { protected $hostname; /** + * The role objects the user has. + * + * @var \Drupal\user\Entity\Role[] + */ + protected $loadedRoles; + + /** * {@inheritdoc} */ public function id() { @@ -247,9 +254,7 @@ public function hasPermission($permission) { return TRUE; } - $roles = \Drupal::entityManager()->getStorage('user_role')->loadMultiple($this->getRoles()); - - foreach ($roles as $role) { + foreach ($this->getRolesAsEntities() as $role) { if ($role->hasPermission($permission)) { return TRUE; } @@ -538,4 +543,18 @@ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { return $fields; } + /** + * Gets and loads the roles. + * + * @return \Drupal\user\Entity\Role[] + * The loaded roles. + */ + protected function getRolesAsEntities() { + if (!isset($this->loadedRoles)) { + $this->loadedRoles = \Drupal::entityManager()->getStorageController('user_role')->loadMultiple($this->getRoles()); + } + + return $this->loadedRoles; + } + }