UserRolesCacheContext.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace Drupal\Core\Cache\Context;
  3. use Drupal\Core\Cache\CacheableMetadata;
  4. /**
  5. * Defines the UserRolesCacheContext service, for "per role" caching.
  6. *
  7. * Only use this cache context when checking explicitly for certain roles. Use
  8. * user.permissions for anything that checks permissions.
  9. *
  10. * Cache context ID: 'user.roles' (to vary by all roles of the current user).
  11. * Calculated cache context ID: 'user.roles:%role', e.g. 'user.roles:anonymous'
  12. * (to vary by the presence/absence of a specific role).
  13. */
  14. class UserRolesCacheContext extends UserCacheContextBase implements CalculatedCacheContextInterface {
  15. /**
  16. * {@inheritdoc}
  17. */
  18. public static function getLabel() {
  19. return t("User's roles");
  20. }
  21. /**
  22. * {@inheritdoc}
  23. */
  24. public function getContext($role = NULL) {
  25. // User 1 does not actually have any special behavior for roles; this is
  26. // added as additional security and backwards compatibility protection for
  27. // SA-CORE-2015-002.
  28. // @todo Remove in Drupal 9.0.0.
  29. if ($this->user->id() == 1) {
  30. return 'is-super-user';
  31. }
  32. if ($role === NULL) {
  33. return implode(',', $this->user->getRoles());
  34. }
  35. else {
  36. return (in_array($role, $this->user->getRoles()) ? '0' : '1');
  37. }
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. public function getCacheableMetadata($role = NULL) {
  43. return (new CacheableMetadata())->setCacheTags(['user:' . $this->user->id()]);
  44. }
  45. }