Commit 46ff3bb2 authored by alexpott's avatar alexpott

Issue #2829588 by damiankloip, Fabianx, markcarver, dawehner, catch: Provide a...

Issue #2829588 by damiankloip, Fabianx, markcarver, dawehner, catch: Provide a "url.path.is_front" cache context to allow contributed themes to move global "is_front" variable back
parent bc7d4f14
......@@ -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']
......
<?php
namespace Drupal\Core\Cache\Context;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Path\PathMatcherInterface;
/**
* Defines a cache context for whether the URL is the front page of the site.
*
* Cache context ID: 'url.path.is_front'.
*/
class IsFrontPathCacheContext implements CacheContextInterface {
/**
* @var \Drupal\Core\Path\PathMatcherInterface
*/
protected $pathMatcher;
/**
* Constructs an IsFrontPathCacheContext object.
*
* @param \Drupal\Core\Path\PathMatcherInterface $path_matcher
*/
public function __construct(PathMatcherInterface $path_matcher) {
$this->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;
}
}
<?php
namespace Drupal\Tests\Core\Cache\Context;
use Drupal\Core\Cache\Context\IsFrontPathCacheContext;
use Drupal\Core\Path\PathMatcherInterface;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass \Drupal\Core\Cache\Context\IsFrontPathCacheContext
* @group Cache
*/
class IsFrontPathCacheContextTest extends UnitTestCase {
/**
* @covers ::getContext
*/
public function testGetContextFront() {
$cache_context = new IsFrontPathCacheContext($this->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;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment