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

8.3.x
Alex Pott 2016-11-26 22:30:04 +00:00
parent bc7d4f144f
commit 46ff3bb2b3
3 changed files with 103 additions and 0 deletions

View File

@ -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']

View File

@ -0,0 +1,52 @@
<?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;
}
}

View File

@ -0,0 +1,46 @@
<?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;
}
}