SessionExistsCacheContext.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace Drupal\Core\Cache\Context;
  3. use Drupal\Core\Cache\CacheableMetadata;
  4. use Drupal\Core\Session\SessionConfigurationInterface;
  5. use Symfony\Component\HttpFoundation\RequestStack;
  6. /**
  7. * Defines the SessionExistsCacheContext service, for "session or not" caching.
  8. *
  9. * Cache context ID: 'session.exists'.
  10. */
  11. class SessionExistsCacheContext implements CacheContextInterface {
  12. /**
  13. * The session configuration.
  14. *
  15. * @var \Drupal\Core\Session\SessionConfigurationInterface
  16. */
  17. protected $sessionConfiguration;
  18. /**
  19. * The request stack.
  20. *
  21. * @var \Symfony\Component\HttpFoundation\RequestStack
  22. */
  23. protected $requestStack;
  24. /**
  25. * Constructs a new SessionExistsCacheContext class.
  26. *
  27. * @param \Drupal\Core\Session\SessionConfigurationInterface $session_configuration
  28. * The session configuration.
  29. * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
  30. * The request stack.
  31. */
  32. public function __construct(SessionConfigurationInterface $session_configuration, RequestStack $request_stack) {
  33. $this->sessionConfiguration = $session_configuration;
  34. $this->requestStack = $request_stack;
  35. }
  36. /**
  37. * {@inheritdoc}
  38. */
  39. public static function getLabel() {
  40. return t('Session exists');
  41. }
  42. /**
  43. * {@inheritdoc}
  44. */
  45. public function getContext() {
  46. return $this->sessionConfiguration->hasSession($this->requestStack->getCurrentRequest()) ? '1' : '0';
  47. }
  48. /**
  49. * {@inheritdoc}
  50. */
  51. public function getCacheableMetadata() {
  52. return new CacheableMetadata();
  53. }
  54. }