3 namespace Drupal\Core\Cache\Context;
5 use Drupal\Core\Cache\CacheableMetadata;
8 * Defines the UserRolesCacheContext service, for "per role" caching.
10 * Only use this cache context when checking explicitly for certain roles. Use
11 * user.permissions for anything that checks permissions.
13 * Cache context ID: 'user.roles' (to vary by all roles of the current user).
14 * Calculated cache context ID: 'user.roles:%role', e.g. 'user.roles:anonymous'
15 * (to vary by the presence/absence of a specific role).
17 class UserRolesCacheContext extends UserCacheContextBase implements CalculatedCacheContextInterface {
22 public static function getLabel() {
23 return t("User's roles");
29 public function getContext($role = NULL) {
30 // User 1 does not actually have any special behavior for roles; this is
31 // added as additional security and backwards compatibility protection for
33 // @todo Remove in Drupal 9.0.0.
34 if ($this->user->id() == 1) {
35 return 'is-super-user';
38 return implode(',', $this->user->getRoles());
41 return (in_array($role, $this->user->getRoles()) ? '0' : '1');
48 public function getCacheableMetadata($role = NULL) {
49 return (new CacheableMetadata())->setCacheTags(['user:' . $this->user->id()]);