BookNavigationCacheContext.php in Drupal 9
File
core/modules/book/src/Cache/BookNavigationCacheContext.php
View source
<?php
namespace Drupal\book\Cache;
use Drupal\Core\DependencyInjection\DeprecatedServicePropertyTrait;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Cache\Context\CacheContextInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\node\NodeInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
class BookNavigationCacheContext implements CacheContextInterface, ContainerAwareInterface {
use ContainerAwareTrait;
use DeprecatedServicePropertyTrait;
protected $routeMatch;
protected $deprecatedProperties = [
'request_stack' => 'request_stack',
];
public function __construct($route_match) {
if (!$route_match instanceof RouteMatchInterface) {
@trigger_error('Passing the request_stack service to ' . __METHOD__ . '() is deprecated in drupal:9.2.0 and will be removed before drupal:10.0.0. The parameter should be an instance of \\Drupal\\Core\\Routing\\RouteMatchInterface instead.', E_USER_DEPRECATED);
$route_match = \Drupal::routeMatch();
}
$this->routeMatch = $route_match;
}
public static function getLabel() {
return t("Book navigation");
}
public function getContext() {
$current_bid = 0;
$node = $this->routeMatch
->getParameter('node');
if ($node instanceof NodeInterface && !empty($node->book['bid'])) {
$current_bid = $node->book['bid'];
}
if ($current_bid === 0) {
return 'book.none';
}
$active_trail = $this->container
->get('book.manager')
->getActiveTrailIds($node->book['bid'], $node->book);
return implode('|', $active_trail);
}
public function getCacheableMetadata() {
$cacheable_metadata = new CacheableMetadata();
$node = $this->routeMatch
->getParameter('node');
if ($node instanceof NodeInterface) {
if (!empty($node->book['bid'])) {
$cacheable_metadata
->addCacheTags([
'bid:' . $node->book['bid'],
]);
}
else {
$cacheable_metadata
->setCacheMaxAge(0);
}
}
return $cacheable_metadata;
}
}