HeadersCacheContext.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace Drupal\Core\Cache\Context;
  3. use Drupal\Core\Cache\CacheableMetadata;
  4. /**
  5. * Defines the HeadersCacheContext service, for "per header" caching.
  6. *
  7. * Cache context ID: 'headers' (to vary by all headers).
  8. * Calculated cache context ID: 'headers:%name', e.g. 'headers:X-Something' (to
  9. * vary by the 'X-Something' header).
  10. */
  11. class HeadersCacheContext extends RequestStackCacheContextBase implements CalculatedCacheContextInterface {
  12. /**
  13. * {@inheritdoc}
  14. */
  15. public static function getLabel() {
  16. return t('HTTP headers');
  17. }
  18. /**
  19. * {@inheritdoc}
  20. */
  21. public function getContext($header = NULL) {
  22. if ($header === NULL) {
  23. $headers = $this->requestStack->getCurrentRequest()->headers->all();
  24. // Order headers by name to have less cache variations.
  25. ksort($headers);
  26. $result = '';
  27. foreach ($headers as $name => $value) {
  28. if ($result) {
  29. $result .= '&';
  30. }
  31. // Sort values to minimize cache variations.
  32. sort($value);
  33. $result .= $name . '=' . implode(',', $value);
  34. }
  35. return $result;
  36. }
  37. elseif ($this->requestStack->getCurrentRequest()->headers->has($header)) {
  38. $value = $this->requestStack->getCurrentRequest()->headers->get($header);
  39. if ($value !== '') {
  40. return $value;
  41. }
  42. return '?valueless?';
  43. }
  44. return '';
  45. }
  46. /**
  47. * {@inheritdoc}
  48. */
  49. public function getCacheableMetadata($header = NULL) {
  50. return new CacheableMetadata();
  51. }
  52. }