MenuActiveTrailsCacheContext.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. namespace Drupal\Core\Cache\Context;
  3. use Drupal\Core\Cache\CacheableMetadata;
  4. use Symfony\Component\DependencyInjection\ContainerAwareInterface;
  5. use Symfony\Component\DependencyInjection\ContainerAwareTrait;
  6. /**
  7. * Defines the MenuActiveTrailsCacheContext service.
  8. *
  9. * This class is container-aware to avoid initializing the 'menu.active_trails'
  10. * service (and its dependencies) when it is not necessary.
  11. */
  12. class MenuActiveTrailsCacheContext implements CalculatedCacheContextInterface, ContainerAwareInterface {
  13. use ContainerAwareTrait;
  14. /**
  15. * {@inheritdoc}
  16. */
  17. public static function getLabel() {
  18. return t("Active menu trail");
  19. }
  20. /**
  21. * {@inheritdoc}
  22. */
  23. public function getContext($menu_name = NULL) {
  24. if (!$menu_name) {
  25. throw new \LogicException('No menu name provided for menu.active_trails cache context.');
  26. }
  27. $active_trail = $this->container->get('menu.active_trail')
  28. ->getActiveTrailIds($menu_name);
  29. return 'menu_trail.' . $menu_name . '|' . implode('|', $active_trail);
  30. }
  31. /**
  32. * {@inheritdoc}
  33. */
  34. public function getCacheableMetadata($menu_name = NULL) {
  35. if (!$menu_name) {
  36. throw new \LogicException('No menu name provided for menu.active_trails cache context.');
  37. }
  38. $cacheable_metadata = new CacheableMetadata();
  39. return $cacheable_metadata->setCacheTags(["config:system.menu.$menu_name"]);
  40. }
  41. }