improvements-2.x-dev/src/Cache/IsEntityPageCacheContext.php
src/Cache/IsEntityPageCacheContext.php
<?php
namespace Drupal\improvements\Cache;
use Drupal\Component\Render\MarkupInterface;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Cache\Context\CalculatedCacheContextInterface;
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Cache context ID: 'is_entity_page' (to vary by whether current page is entity page or not).
* Calculated cache context ID: 'is_entity_page:%entity_type', e.g.'is_entity_page:node' (to vary by whether current page is node page or not) or 'is_entity_page:node,taxonomy_term' (to vary by whether current page is node/taxonomy_term page or not).
*/
class IsEntityPageCacheContext implements CalculatedCacheContextInterface {
protected RouteMatchInterface $routeMatch;
/**
* Class constructor.
*/
public function __construct(RouteMatchInterface $route_match) {
$this->routeMatch = $route_match;
}
/**
* {@inheritdoc}
*/
public static function getLabel(): MarkupInterface {
return t('Is entity page');
}
/**
* {@inheritdoc}
*/
public function getContext($entity_type_id = NULL) {
if (preg_match('/^entity\.(.+)\.canonical$/', $this->routeMatch->getRouteName(), $matches)) {
if ($entity_type_id) {
$entity_type_ids = explode(',', $entity_type_id);
$matched_entity_type_id = $matches[1];
return (string)(int)in_array($matched_entity_type_id, $entity_type_ids);
}
return '1';
}
return '0';
}
/**
* {@inheritdoc}
*/
public function getCacheableMetadata($entity_type_id = NULL) {
return new CacheableMetadata();
}
}
