Issue #2512718 by Berdir, pfrenssen, Wim Leers, Fabianx, dawehner, catch, effulgentsia, plach, Gábor Hojtsy: EntityManager::getTranslationFromContext() should add the content language cache context to the entity

8.0.x
Nathaniel Catchpole 2015-07-07 17:08:02 +01:00
parent 7468b58512
commit a362252a2b
29 changed files with 331 additions and 35 deletions

View File

@ -25,6 +25,9 @@ use Drupal\Core\Session\AccountInterface;
*
* When using ::orIf() and ::andIf(), cacheability metadata will be merged
* accordingly as well.
*
* @todo Use RefinableCacheableDependencyInterface and the corresponding trait in
* https://www.drupal.org/node/2526326.
*/
abstract class AccessResult implements AccessResultInterface, CacheableDependencyInterface {

View File

@ -10,6 +10,9 @@ namespace Drupal\Core\Cache;
* Defines a generic class for passing cacheability metadata.
*
* @ingroup cache
*
* @todo Use RefinableCacheableDependencyInterface and the corresponding trait in
* https://www.drupal.org/node/2526326.
*/
class CacheableMetadata implements CacheableDependencyInterface {

View File

@ -0,0 +1,55 @@
<?php
/**
* @file
* Contains \Drupal\Core\Cache\RefinableCacheableDependencyInterface.
*/
namespace Drupal\Core\Cache;
/**
* Allows to add cacheability metadata to an object for the current runtime.
*
* This must be used when changing an object in a way that affects its
* cacheability. For example, when changing the active translation of an entity
* based on the current content language then a cache context for that must be
* added.
*/
interface RefinableCacheableDependencyInterface extends CacheableDependencyInterface {
/**
* Adds cache contexts.
*
* @param string[] $cache_contexts
* The cache contexts to be added.
*
* @return $this
*/
public function addCacheContexts(array $cache_contexts);
/**
* Adds cache tags.
*
* @param string[] $cache_tags
* The cache tags to be added.
*
* @return $this
*/
public function addCacheTags(array $cache_tags);
/**
* Merges the maximum age (in seconds) with the existing maximum age.
*
* The max age will be set to the given value if it is lower than the existing
* value.
*
* @param int $max_age
* The max age to associate.
*
* @return $this
*
* @throws \InvalidArgumentException
* Thrown if a non-integer value is supplied.
*/
public function mergeCacheMaxAge($max_age);
}

View File

@ -0,0 +1,60 @@
<?php
/**
* @file
* Contains \Drupal\Core\Cache\RefinableCacheableDependencyTrait.
*/
namespace Drupal\Core\Cache;
/**
* Trait for \Drupal\Core\Cache\RefinableCacheableDependencyInterface.
*/
trait RefinableCacheableDependencyTrait {
/**
* Cache contexts.
*
* @var string[]
*/
protected $cacheContexts = [];
/**
* Cache tags.
*
* @var string[]
*/
protected $cacheTags = [];
/**
* Cache max-age.
*
* @var int
*/
protected $cacheMaxAge = Cache::PERMANENT;
/**
* {@inheritdoc}
*/
public function addCacheContexts(array $cache_contexts) {
$this->cacheContexts = Cache::mergeContexts($this->cacheContexts, $cache_contexts);
return $this;
}
/**
* {@inheritdoc}
*/
public function addCacheTags(array $cache_tags) {
$this->cacheTags = Cache::mergeTags($this->cacheTags, $cache_tags);
return $this;
}
/**
* {@inheritdoc}
*/
public function mergeCacheMaxAge($max_age) {
$this->cacheMaxAge = Cache::mergeMaxAges($this->cacheMaxAge, $max_age);
return $this;
}
}

View File

@ -193,7 +193,7 @@ abstract class ConfigEntityBase extends Entity implements ConfigEntityInterface
*/
public function disable() {
// An entity was disabled, invalidate its own cache tag.
Cache::invalidateTags($this->getCacheTags());
Cache::invalidateTags($this->getCacheTagsToInvalidate());
return $this->setStatus(FALSE);
}
@ -409,7 +409,7 @@ abstract class ConfigEntityBase extends Entity implements ConfigEntityInterface
/**
* {@inheritdoc}
*/
public function getCacheTags() {
public function getCacheTagsToInvalidate() {
// Use cache tags that match the underlying config object's name.
// @see \Drupal\Core\Config\ConfigBase::getCacheTags()
return ['config:' . $this->getConfigDependencyName()];

View File

@ -101,7 +101,7 @@ class DateFormat extends ConfigEntityBase implements DateFormatInterface {
/**
* {@inheritdoc}
*/
public function getCacheTags() {
public function getCacheTagsToInvalidate() {
return ['rendered'];
}

View File

@ -8,6 +8,7 @@
namespace Drupal\Core\Entity;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\RefinableCacheableDependencyTrait;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\Component\Utility\Unicode;
@ -24,6 +25,8 @@ use Drupal\Core\Url;
*/
abstract class Entity implements EntityInterface {
use RefinableCacheableDependencyTrait;
use DependencySerializationTrait {
__sleep as traitSleep;
}
@ -440,23 +443,36 @@ abstract class Entity implements EntityInterface {
* {@inheritdoc}
*/
public function getCacheContexts() {
return [];
return $this->cacheContexts;
}
/**
* {@inheritdoc}
*/
public function getCacheTags() {
public function getCacheTagsToInvalidate() {
// @todo Add bundle-specific listing cache tag?
// https://www.drupal.org/node/2145751
if ($this->isNew()) {
return [];
}
return [$this->entityTypeId . ':' . $this->id()];
}
/**
* {@inheritdoc}
*/
public function getCacheTags() {
if ($this->cacheTags) {
return Cache::mergeTags($this->getCacheTagsToInvalidate(), $this->cacheTags);
}
return $this->getCacheTagsToInvalidate();
}
/**
* {@inheritdoc}
*/
public function getCacheMaxAge() {
return Cache::PERMANENT;
return $this->cacheMaxAge;
}
/**
@ -511,7 +527,7 @@ abstract class Entity implements EntityInterface {
}
if ($update) {
// An existing entity was updated, also invalidate its unique cache tag.
$tags = Cache::mergeTags($tags, $this->getCacheTags());
$tags = Cache::mergeTags($tags, $this->getCacheTagsToInvalidate());
}
Cache::invalidateTags($tags);
}
@ -532,7 +548,7 @@ abstract class Entity implements EntityInterface {
// other pages than the one it's on. The one it's on is handled by its own
// cache tag, but subsequent list pages would not be invalidated, hence we
// must invalidate its list cache tags as well.)
$tags = Cache::mergeTags($tags, $entity->getCacheTags());
$tags = Cache::mergeTags($tags, $entity->getCacheTagsToInvalidate());
}
Cache::invalidateTags($tags);
}

View File

@ -101,6 +101,12 @@ class EntityForm extends FormBase implements EntityFormInterface {
$this->init($form_state);
}
// Ensure that edit forms have the correct cacheability metadata so they can
// be cached.
if (!$this->entity->isNew()) {
\Drupal::service('renderer')->addCacheableDependency($form, $this->entity);
}
// Retrieve the form array using the possibly updated entity in form state.
$form = $this->form($form, $form_state);

View File

@ -9,13 +9,14 @@ namespace Drupal\Core\Entity;
use Drupal\Core\Access\AccessibleInterface;
use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\Core\Cache\RefinableCacheableDependencyInterface;
/**
* Defines a common interface for all entity objects.
*
* @ingroup entity_api
*/
interface EntityInterface extends AccessibleInterface, CacheableDependencyInterface {
interface EntityInterface extends AccessibleInterface, CacheableDependencyInterface, RefinableCacheableDependencyInterface {
/**
* Gets the entity UUID (Universally Unique Identifier).
@ -348,6 +349,19 @@ interface EntityInterface extends AccessibleInterface, CacheableDependencyInterf
*/
public function getOriginalId();
/**
* Returns the cache tags that should be used to invalidate caches.
*
* This will not return additional cache tags added through addCacheTags().
*
* @return string[]
* Set of cache tags.
*
* @see \Drupal\Core\Cache\RefinableCacheableDependencyInterface::addCacheTags()
* @see \Drupal\Core\Cache\CacheableDependencyInterface::getCacheTags()
*/
public function getCacheTagsToInvalidate();
/**
* Sets the original ID.
*

View File

@ -969,6 +969,7 @@ class EntityManager extends DefaultPluginManager implements EntityManagerInterfa
if ($entity instanceof TranslatableInterface && count($entity->getTranslationLanguages()) > 1) {
if (empty($langcode)) {
$langcode = $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();
$entity->addCacheContexts(['languages:' . LanguageInterface::TYPE_CONTENT]);
}
// Retrieve language fallback candidates to perform the entity language

View File

@ -117,14 +117,10 @@ class EntityViewBuilder extends EntityHandlerBase implements EntityHandlerInterf
* {@inheritdoc}
*/
public function viewMultiple(array $entities = array(), $view_mode = 'full', $langcode = NULL) {
if (!isset($langcode)) {
$langcode = $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId();
}
$build_list = array(
'#sorted' => TRUE,
'#pre_render' => array(array($this, 'buildMultiple')),
'#langcode' => $langcode,
'#langcode' => $langcode ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)->getId(),
);
$weight = 0;
foreach ($entities as $key => $entity) {
@ -133,9 +129,10 @@ class EntityViewBuilder extends EntityHandlerBase implements EntityHandlerInterf
$entity = $this->entityManager->getTranslationFromContext($entity, $langcode);
// Set build defaults.
$build_list[$key] = $this->getBuildDefaults($entity, $view_mode, $langcode);
$entity_langcode = $entity->language()->getId();
$build_list[$key] = $this->getBuildDefaults($entity, $view_mode, $entity_langcode);
$entityType = $this->entityTypeId;
$this->moduleHandler()->alter(array($entityType . '_build_defaults', 'entity_build_defaults'), $build_list[$key], $entity, $view_mode, $langcode);
$this->moduleHandler()->alter(array($entityType . '_build_defaults', 'entity_build_defaults'), $build_list[$key], $entity, $view_mode, $entity_langcode);
$build_list[$key]['#weight'] = $weight++;
}

View File

@ -225,13 +225,13 @@ class Item extends ContentEntityBase implements ItemInterface {
// handles the regular cases. The Item entity has one special case: a newly
// created Item is *also* associated with a Feed, so we must invalidate the
// associated Feed's cache tag.
Cache::invalidateTags($this->getCacheTags());
Cache::invalidateTags($this->getCacheTagsToInvalidate());
}
/**
* {@inheritdoc}
*/
public function getCacheTags() {
public function getCacheTagsToInvalidate() {
return Feed::load($this->getFeedId())->getCacheTags();
}

View File

@ -246,7 +246,7 @@ class Block extends ConfigEntityBase implements BlockInterface, EntityWithPlugin
// so we must invalidate the associated block's cache tag (which includes
// the theme cache tag).
if (!$update) {
Cache::invalidateTags($this->getCacheTags());
Cache::invalidateTags($this->getCacheTagsToInvalidate());
}
}

View File

@ -194,7 +194,7 @@ class BlockViewBuilderTest extends KernelTestBase {
// Enable the block view alter hook that adds a suffix, for basic testing.
\Drupal::state()->set('block_test_view_alter_suffix', TRUE);
Cache::invalidateTags($this->block->getCacheTags());
Cache::invalidateTags($this->block->getCacheTagsToInvalidate());
$build = $this->getBlockRenderArray();
$this->assertTrue(isset($build['#suffix']) && $build['#suffix'] === '<br>Goodbye!', 'A block with content is altered.');
$this->assertIdentical($this->renderer->renderRoot($build), 'Llamas &gt; unicorns!<br>Goodbye!');
@ -206,7 +206,7 @@ class BlockViewBuilderTest extends KernelTestBase {
$request->setMethod('GET');
\Drupal::state()->set('block_test.content', NULL);
Cache::invalidateTags($this->block->getCacheTags());
Cache::invalidateTags($this->block->getCacheTagsToInvalidate());
$default_keys = array('entity_view', 'block', 'test_block');
$default_tags = array('block_view', 'config:block.block.test_block');

View File

@ -71,11 +71,9 @@ class CommentViewBuilder extends EntityViewBuilder {
->getFieldDefinition($entity->getFieldName())
->getSetting('default_mode') === CommentManagerInterface::COMMENT_MODE_THREADED;
// If threading is enabled, don't render cache individual comments, but do
// keep the cache tags, so they can bubble up.
// keep the cacheability metadata, so it can bubble up.
if ($build['#comment_threaded']) {
$cache_tags = $build['#cache']['tags'];
$build['#cache'] = [];
$build['#cache']['tags'] = $cache_tags;
unset($build['#cache']['keys']);
}
return $build;

View File

@ -32,6 +32,18 @@ class CommentTranslationUITest extends ContentTranslationUITestBase {
*/
protected $adminUser;
/**
* {inheritdoc}
*/
protected $defaultCacheContexts = [
'languages:language_interface',
'theme',
'user.permissions',
'timezone',
'url.query_args.pagers:0',
'user.roles'
];
/**
* Modules to install.
*

View File

@ -86,7 +86,7 @@ class ContactLinkTest extends ViewTestBase {
// Disable contact link for no_contact.
$this->userData->set('contact', $no_contact_account->id(), 'enabled', FALSE);
// @todo Remove cache invalidation in https://www.drupal.org/node/2477903.
Cache::invalidateTags($no_contact_account->getCacheTags());
Cache::invalidateTags($no_contact_account->getCacheTagsToInvalidate());
$this->drupalGet('test-contact-link');
$this->assertContactLinks($accounts, array('root', 'admin'));
}

View File

@ -7,18 +7,22 @@
namespace Drupal\content_translation\Tests;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Language\Language;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Url;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\system\Tests\Cache\AssertPageCacheContextsAndTagsTrait;
/**
* Tests the Content Translation UI.
*/
abstract class ContentTranslationUITestBase extends ContentTranslationTestBase {
use AssertPageCacheContextsAndTagsTrait;
/**
* The id of the entity being translated.
*
@ -33,6 +37,15 @@ abstract class ContentTranslationUITestBase extends ContentTranslationTestBase {
*/
protected $testLanguageSelector = TRUE;
/**
* Default cache contexts expected on a non-translated entity.
*
* Cache contexts will not be checked if this list is empty.
*
* @var string[]
*/
protected $defaultCacheContexts = ['languages:language_interface', 'theme', 'user.permissions'];
/**
* Tests the basic translation UI.
*/
@ -64,6 +77,11 @@ abstract class ContentTranslationUITestBase extends ContentTranslationTestBase {
$this->assertTrue($entity, 'Entity found in the database.');
$this->drupalGet($entity->urlInfo());
$this->assertResponse(200, 'Entity URL is valid.');
// Ensure that the content language cache context is not yet added to the
// page.
$this->assertCacheContexts($this->defaultCacheContexts);
$this->drupalGet($entity->urlInfo('drupal:content-translation-overview'));
$this->assertNoText('Source language', 'Source language column correctly hidden.');
@ -87,9 +105,14 @@ abstract class ContentTranslationUITestBase extends ContentTranslationTestBase {
], array('language' => $language));
$this->drupalPostForm($add_url, $this->getEditValues($values, $langcode), $this->getFormSubmitActionForNewTranslation($entity, $langcode));
// Get the entity and reset its cache, so that the new translation gets the
// updated values.
// Ensure that the content language cache context is not yet added to the
// page.
$entity = entity_load($this->entityTypeId, $this->entityId, TRUE);
$this->drupalGet($entity->urlInfo());
$this->assertCacheContexts(Cache::mergeContexts(['languages:language_content'], $this->defaultCacheContexts));
// Reset the cache of the entity, so that the new translation gets the
// updated values.
$metadata_source_translation = $this->manager->getTranslationMetadata($entity->getTranslation($default_langcode));
$metadata_target_translation = $this->manager->getTranslationMetadata($entity->getTranslation($langcode));

View File

@ -267,7 +267,7 @@ class ImageStyle extends ConfigEntityBase implements ImageStyleInterface, Entity
// Clear caches so that formatters may be added for this style.
drupal_theme_rebuild();
Cache::invalidateTags($this->getCacheTags());
Cache::invalidateTags($this->getCacheTagsToInvalidate());
return $this;
}

View File

@ -17,6 +17,11 @@ use Drupal\menu_link_content\Entity\MenuLinkContent;
*/
class MenuLinkContentTranslationUITest extends ContentTranslationUITestBase {
/**
* {inheritdoc}
*/
protected $defaultCacheContexts = ['languages:language_interface', 'theme', 'user.permissions', 'user.roles:authenticated'];
/**
* Modules to enable.
*

View File

@ -21,6 +21,21 @@ use Drupal\language\Entity\ConfigurableLanguage;
*/
class NodeTranslationUITest extends ContentTranslationUITestBase {
/**
* {inheritdoc}
*/
protected $defaultCacheContexts = [
'languages:language_interface',
'theme',
'user.permissions',
'route.menu_active_trails:account',
'route.menu_active_trails:footer',
'route.menu_active_trails:main',
'route.menu_active_trails:tools',
'timezone',
'user.roles'
];
/**
* Modules to enable.
*

View File

@ -102,7 +102,7 @@ class Shortcut extends ContentEntityBase implements ShortcutInterface {
// newly created shortcut is *also* added to a shortcut set, so we must
// invalidate the associated shortcut set's cache tag.
if (!$update) {
Cache::invalidateTags($this->getCacheTags());
Cache::invalidateTags($this->getCacheTagsToInvalidate());
}
}
@ -178,7 +178,7 @@ class Shortcut extends ContentEntityBase implements ShortcutInterface {
/**
* {@inheritdoc}
*/
public function getCacheTags() {
public function getCacheTagsToInvalidate() {
return $this->shortcut_set->entity->getCacheTags();
}

View File

@ -18,6 +18,11 @@ use Drupal\Core\Language\Language;
*/
class ShortcutTranslationUITest extends ContentTranslationUITestBase {
/**
* {inheritdoc}
*/
protected $defaultCacheContexts = ['languages:language_interface', 'theme', 'user'];
/**
* Modules to enable.
*

View File

@ -571,7 +571,7 @@ abstract class EntityCacheTagsTestBase extends PageCacheTagsTestBase {
// a cache miss for every route except the ones for the non-referencing
// entity and the empty entity listing.
$this->pass("Test invalidation of referenced entity's cache tag.", 'Debug');
Cache::invalidateTags($this->entity->getCacheTags());
Cache::invalidateTags($this->entity->getCacheTagsToInvalidate());
$this->verifyPageCache($referencing_entity_url, 'MISS');
$this->verifyPageCache($listing_url, 'MISS');
$this->verifyPageCache($nonempty_entity_listing_url, 'MISS');

View File

@ -121,7 +121,7 @@ abstract class EntityWithUriCacheTagsTestBase extends EntityCacheTagsTestBase {
// Verify that after invalidating the entity's cache tag directly, there is
// a cache miss.
$this->pass("Test invalidation of entity's cache tag.", 'Debug');
Cache::invalidateTags($this->entity->getCacheTags());
Cache::invalidateTags($this->entity->getCacheTagsToInvalidate());
$this->verifyPageCache($entity_url, 'MISS');
// Verify a cache hit.

View File

@ -153,7 +153,7 @@ abstract class CachePluginBase extends PluginBase {
* Clear out cached data for a view.
*/
public function cacheFlush() {
Cache::invalidateTags($this->view->storage->getCacheTags());
Cache::invalidateTags($this->view->storage->getCacheTagsToInvalidate());
}
/**

View File

@ -197,7 +197,7 @@ class CacheTagTest extends PluginTestBase {
$view->destroy();
// Invalidate the views cache tags in order to invalidate the render
// caching.
\Drupal::service('cache_tags.invalidator')->invalidateTags($view->storage->getCacheTags());
\Drupal::service('cache_tags.invalidator')->invalidateTags($view->storage->getCacheTagsToInvalidate());
$build = $view->buildRenderable();
$renderer->renderPlain($build);

View File

@ -1336,4 +1336,32 @@ class ViewUI implements ViewEntityInterface {
return $this->storage->hasTrustedData();
}
/**
* {@inheritdoc}
*/
public function addCacheContexts(array $cache_contexts) {
return $this->storage->addCacheContexts($cache_contexts);
}
/**
* {@inheritdoc}
*/
public function mergeCacheMaxAge($max_age) {
return $this->storage->mergeCacheMaxAge($max_age);
}
/**
* {@inheritdoc}
*/
public function getCacheTagsToInvalidate() {
return $this->storage->getCacheTagsToInvalidate();
}
/**
* {@inheritdoc}
*/
public function addCacheTags(array $cache_tags) {
return $this->storage->addCacheTags($cache_tags);
}
}

View File

@ -8,6 +8,7 @@
namespace Drupal\Tests\Core\Entity;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Cache\Cache;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\Entity\Entity;
use Drupal\Core\Entity\Exception\NoCorrespondingEntityClassException;
@ -486,4 +487,58 @@ class EntityUnitTest extends UnitTestCase {
public function testReferencedEntities() {
$this->assertSame(array(), $this->entity->referencedEntities());
}
/**
* @covers ::getCacheTags
* @covers ::getCacheTagsToInvalidate
* @covers ::addCacheTags
*/
public function testCacheTags() {
// Ensure that both methods return the same by default.
$this->assertEquals([$this->entityTypeId . ':' . 1], $this->entity->getCacheTags());
$this->assertEquals([$this->entityTypeId . ':' . 1], $this->entity->getCacheTagsToInvalidate());
// Add an additional cache tag and make sure only getCacheTags() returns
// that.
$this->entity->addCacheTags(['additional_cache_tag']);
$this->assertEquals(['additional_cache_tag', $this->entityTypeId . ':' . 1], $this->entity->getCacheTags());
$this->assertEquals([$this->entityTypeId . ':' . 1], $this->entity->getCacheTagsToInvalidate());
}
/**
* @covers ::getCacheContexts
* @covers ::addCacheContexts
*/
public function testCacheContexts() {
$cache_contexts_manager = $this->getMockBuilder('Drupal\Core\Cache\Context\CacheContextsManager')
->disableOriginalConstructor()
->getMock();
$container = new ContainerBuilder();
$container->set('cache_contexts_manager', $cache_contexts_manager);
\Drupal::setContainer($container);
// There are no cache contexts by default.
$this->assertEquals([], $this->entity->getCacheContexts());
// Add an additional cache context.
$this->entity->addCacheContexts(['user']);
$this->assertEquals(['user'], $this->entity->getCacheContexts());
}
/**
* @covers ::getCacheMaxAge
* @covers ::mergeCacheMaxAge
*/
public function testCacheMaxAge() {
// Cache max age is permanent by default.
$this->assertEquals(Cache::PERMANENT, $this->entity->getCacheMaxAge());
// Set two cache max ages, the lower value is the one that needs to be
// returned.
$this->entity->mergeCacheMaxAge(600);
$this->entity->mergeCacheMaxAge(1800);
$this->assertEquals(600, $this->entity->getCacheMaxAge());
}
}