AccountPermissionsCacheContext.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace Drupal\Core\Cache\Context;
  3. use Drupal\Core\Cache\CacheableMetadata;
  4. use Drupal\Core\Session\AccountInterface;
  5. use Drupal\Core\Session\PermissionsHashGeneratorInterface;
  6. /**
  7. * Defines the AccountPermissionsCacheContext service, for "per permission" caching.
  8. *
  9. * Cache context ID: 'user.permissions'.
  10. */
  11. class AccountPermissionsCacheContext extends UserCacheContextBase implements CacheContextInterface {
  12. /**
  13. * The permissions hash generator.
  14. *
  15. * @var \Drupal\Core\Session\PermissionsHashGeneratorInterface
  16. */
  17. protected $permissionsHashGenerator;
  18. /**
  19. * Constructs a new UserCacheContext service.
  20. *
  21. * @param \Drupal\Core\Session\AccountInterface $user
  22. * The current user.
  23. * @param \Drupal\Core\Session\PermissionsHashGeneratorInterface $permissions_hash_generator
  24. * The permissions hash generator.
  25. */
  26. public function __construct(AccountInterface $user, PermissionsHashGeneratorInterface $permissions_hash_generator) {
  27. $this->user = $user;
  28. $this->permissionsHashGenerator = $permissions_hash_generator;
  29. }
  30. /**
  31. * {@inheritdoc}
  32. */
  33. public static function getLabel() {
  34. return t("Account's permissions");
  35. }
  36. /**
  37. * {@inheritdoc}
  38. */
  39. public function getContext() {
  40. return $this->permissionsHashGenerator->generate($this->user);
  41. }
  42. /**
  43. * {@inheritdoc}
  44. */
  45. public function getCacheableMetadata() {
  46. $cacheable_metadata = new CacheableMetadata();
  47. // The permissions hash changes when:
  48. // - a user is updated to have different roles;
  49. $tags = ['user:' . $this->user->id()];
  50. // - a role is updated to have different permissions.
  51. foreach ($this->user->getRoles() as $rid) {
  52. $tags[] = "config:user.role.$rid";
  53. }
  54. return $cacheable_metadata->setCacheTags($tags);
  55. }
  56. }