I am working with Mobile Detect module and from what I understand, we need to manually add the cache context mobile_detect_is_mobile
in order to have the page cached differently based on the user device type. I was able to make it work by applying the cache context using a preprocess on my paragraph like so :
function hook_preprocess_paragraph(&$variables){
$variables['#cache']['contexts'][] = 'mobile_detect_is_mobile';
}
Although, I don't like the idea of adding the context at the preprocess level and I was looking to have a more global solution by using an EventSubscriber that checks the path and apply the cache context for specific paths. It seems like the cache context is not taken in consideration. Here my EventSubscriber :
class MobileDetectSubscriber implements EventSubscriberInterface {
/**
* @var \Symfony\Component\HttpFoundation\Request
*/
protected $request;
/**
* @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
*/
public function __construct(RequestStack $request_stack) {
$this->request = $request_stack->getCurrentRequest();;
}
/**
* @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
* The event to process.
*/
public function onRespond(FilterResponseEvent $event) {
if (!$event
->isMasterRequest()) {
return;
}
$response = $event
->getResponse();
if (!$response instanceof CacheableResponseInterface) {
return;
}
if($this->request->getRequestUri() == "/"){
$mobile_detect = new CacheableMetadata();
$mobile_detect->setCacheContexts(['mobile_detect_is_mobile']);
$response->addCacheableDependency($mobile_detect);
}
}
/**
* @return array
* An array of event listener definitions.
*/
public static function getSubscribedEvents() {
// Priority 5, so that it runs before FinishResponseSubscriber, but after
// event subscribers that add the associated cacheability metadata (which
// have priority 10). This one is conditional, so must run after those.
$events[KernelEvents::RESPONSE][] = ['onRespond', 5];
return $events;
}
}
What am I missing ?