QueryArgsCacheContext.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. namespace Drupal\Core\Cache\Context;
  3. use Drupal\Core\Cache\CacheableMetadata;
  4. /**
  5. * Defines the QueryArgsCacheContext service, for "per query args" caching.
  6. *
  7. * Cache context ID: 'url.query_args' (to vary by all query arguments).
  8. * Calculated cache context ID: 'url.query_args:%key', e.g.'url.query_args:foo'
  9. * (to vary by the 'foo' query argument).
  10. */
  11. class QueryArgsCacheContext extends RequestStackCacheContextBase implements CalculatedCacheContextInterface {
  12. /**
  13. * {@inheritdoc}
  14. */
  15. public static function getLabel() {
  16. return t('Query arguments');
  17. }
  18. /**
  19. * {@inheritdoc}
  20. */
  21. public function getContext($query_arg = NULL) {
  22. if ($query_arg === NULL) {
  23. // All arguments requested. Use normalized query string to minimize
  24. // variations.
  25. $value = $this->requestStack->getCurrentRequest()->getQueryString();
  26. return ($value !== NULL) ? $value : '';
  27. }
  28. elseif ($this->requestStack->getCurrentRequest()->query->has($query_arg)) {
  29. $value = $this->requestStack->getCurrentRequest()->query->get($query_arg);
  30. if (is_array($value)) {
  31. return http_build_query($value);
  32. }
  33. elseif ($value !== '') {
  34. return $value;
  35. }
  36. return '?valueless?';
  37. }
  38. return '';
  39. }
  40. /**
  41. * {@inheritdoc}
  42. */
  43. public function getCacheableMetadata($query_arg = NULL) {
  44. return new CacheableMetadata();
  45. }
  46. }