3 namespace Drupal\Core\Cache\Context;
5 use Drupal\Core\Cache\CacheableMetadata;
6 use Drupal\Core\Session\AccountInterface;
7 use Drupal\Core\Session\PermissionsHashGeneratorInterface;
10 * Defines the AccountPermissionsCacheContext service, for "per permission" caching.
12 * Cache context ID: 'user.permissions'.
14 class AccountPermissionsCacheContext extends UserCacheContextBase implements CacheContextInterface {
17 * The permissions hash generator.
19 * @var \Drupal\Core\Session\PermissionsHashGeneratorInterface
21 protected $permissionsHashGenerator;
24 * Constructs a new UserCacheContext service.
26 * @param \Drupal\Core\Session\AccountInterface $user
28 * @param \Drupal\Core\Session\PermissionsHashGeneratorInterface $permissions_hash_generator
29 * The permissions hash generator.
31 public function __construct(AccountInterface $user, PermissionsHashGeneratorInterface $permissions_hash_generator) {
33 $this->permissionsHashGenerator = $permissions_hash_generator;
39 public static function getLabel() {
40 return t("Account's permissions");
46 public function getContext() {
47 return $this->permissionsHashGenerator->generate($this->user);
53 public function getCacheableMetadata() {
54 $cacheable_metadata = new CacheableMetadata();
56 // The permissions hash changes when:
57 // - a user is updated to have different roles;
58 $tags = ['user:' . $this->user->id()];
59 // - a role is updated to have different permissions.
60 foreach ($this->user->getRoles() as $rid) {
61 $tags[] = "config:user.role.$rid";
64 return $cacheable_metadata->setCacheTags($tags);