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