diff --git a/core/core.services.yml b/core/core.services.yml index 5c42b23e055..5b0de757832 100644 --- a/core/core.services.yml +++ b/core/core.services.yml @@ -93,6 +93,11 @@ services: arguments: ['@request_stack'] tags: - { name: cache.context } + cache_context.url.path.is_front: + class: Drupal\Core\Cache\Context\IsFrontPathCacheContext + arguments: ['@path.matcher'] + tags: + - { name: cache.context } cache_context.url.query_args: class: Drupal\Core\Cache\Context\QueryArgsCacheContext arguments: ['@request_stack'] diff --git a/core/lib/Drupal/Core/Cache/Context/IsFrontPathCacheContext.php b/core/lib/Drupal/Core/Cache/Context/IsFrontPathCacheContext.php new file mode 100644 index 00000000000..141b13a63f1 --- /dev/null +++ b/core/lib/Drupal/Core/Cache/Context/IsFrontPathCacheContext.php @@ -0,0 +1,52 @@ +pathMatcher = $path_matcher; + } + + /** + * {@inheritdoc} + */ + public static function getLabel() { + return t('Is front page'); + } + + /** + * {@inheritdoc} + */ + public function getContext() { + return 'is_front.' . (int) $this->pathMatcher->isFrontPage(); + } + + /** + * {@inheritdoc} + */ + public function getCacheableMetadata() { + $metadata = new CacheableMetadata(); + $metadata->addCacheTags(['config:system.site']); + return $metadata; + } + +} diff --git a/core/tests/Drupal/Tests/Core/Cache/Context/IsFrontPathCacheContextTest.php b/core/tests/Drupal/Tests/Core/Cache/Context/IsFrontPathCacheContextTest.php new file mode 100644 index 00000000000..5ccb18566f3 --- /dev/null +++ b/core/tests/Drupal/Tests/Core/Cache/Context/IsFrontPathCacheContextTest.php @@ -0,0 +1,46 @@ +createPathMatcher(TRUE)->reveal()); + $this->assertSame('is_front.1', $cache_context->getContext()); + } + + /** + * @covers ::getContext + */ + public function testGetContextNotFront() { + $cache_context = new IsFrontPathCacheContext($this->createPathMatcher(FALSE)->reveal()); + $this->assertSame('is_front.0', $cache_context->getContext()); + } + + /** + * Creates a PathMatcherInterface prophecy. + * + * @param bool $is_front + * + * @return \Prophecy\Prophecy\ObjectProphecy + */ + protected function createPathMatcher($is_front) { + $path_matcher = $this->prophesize(PathMatcherInterface::class); + $path_matcher->isFrontPage() + ->willReturn($is_front); + + return $path_matcher; + } + +}