3 namespace Drupal\book\Cache;
5 use Drupal\Core\Cache\CacheableMetadata;
6 use Drupal\Core\Cache\Context\CacheContextInterface;
7 use Symfony\Component\DependencyInjection\ContainerAwareInterface;
8 use Symfony\Component\DependencyInjection\ContainerAwareTrait;
9 use Symfony\Component\HttpFoundation\RequestStack;
12 * Defines the book navigation cache context service.
14 * Cache context ID: 'route.book_navigation'.
16 * This allows for book navigation location-aware caching. It depends on:
17 * - whether the current route represents a book node at all
18 * - and if so, where in the book hierarchy we are
20 * This class is container-aware to avoid initializing the 'book.manager'
21 * service when it is not necessary.
23 class BookNavigationCacheContext implements CacheContextInterface, ContainerAwareInterface {
25 use ContainerAwareTrait;
30 * @var \Symfony\Component\HttpFoundation\RequestStack
32 protected $requestStack;
35 * Constructs a new BookNavigationCacheContext service.
37 * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
40 public function __construct(RequestStack $request_stack) {
41 $this->requestStack = $request_stack;
47 public static function getLabel() {
48 return t("Book navigation");
54 public function getContext() {
55 // Find the current book's ID.
57 if ($node = $this->requestStack->getCurrentRequest()->get('node')) {
58 $current_bid = empty($node->book['bid']) ? 0 : $node->book['bid'];
61 // If we're not looking at a book node, then we're not navigating a book.
62 if ($current_bid === 0) {
66 // If we're looking at a book node, get the trail for that node.
67 $active_trail = $this->container->get('book.manager')
68 ->getActiveTrailIds($node->book['bid'], $node->book);
69 return implode('|', $active_trail);
75 public function getCacheableMetadata() {
76 // The book active trail depends on the node and data attached to it.
77 // That information is however not stored as part of the node.
78 $cacheable_metadata = new CacheableMetadata();
79 if ($node = $this->requestStack->getCurrentRequest()->get('node')) {
80 // If the node is part of a book then we can use the cache tag for that
81 // book. If not, then it can't be optimized away.
82 if (!empty($node->book['bid'])) {
83 $cacheable_metadata->addCacheTags(['bid:' . $node->book['bid']]);
86 $cacheable_metadata->setCacheMaxAge(0);
89 return $cacheable_metadata;