Commit a362252a authored by catch's avatar catch

Issue #2512718 by Berdir, pfrenssen, Wim Leers, Fabianx, dawehner, catch,...

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
parent 7468b585
......@@ -25,6 +25,9 @@
*
* 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 {
......
......@@ -10,6 +10,9 @@
* 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 {
......
<?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);
}
<?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;
}
}
......@@ -193,7 +193,7 @@ public function enable() {
*/
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 @@ public function link($text = NULL, $rel = 'edit-form', array $options = []) {
/**
* {@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()];
......
......@@ -101,7 +101,7 @@ public static function sort(ConfigEntityInterface $a, ConfigEntityInterface $b)
/**
* {@inheritdoc}
*/
public function getCacheTags() {
public function getCacheTagsToInvalidate() {
return ['rendered'];
}
......
......@@ -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 @@
*/
abstract class Entity implements EntityInterface {
use RefinableCacheableDependencyTrait;
use DependencySerializationTrait {
__sleep as traitSleep;
}
......@@ -440,23 +443,36 @@ public function referencedEntities() {
* {@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 @@ protected function invalidateTagsOnSave($update) {
}
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 @@ protected static function invalidateTagsOnDelete(EntityTypeInterface $entity_typ
// 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);
}
......
......@@ -101,6 +101,12 @@ public function buildForm(array $form, FormStateInterface $form_state) {
$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);
......
......@@ -9,13 +9,14 @@
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 @@ public function referencedEntities();
*/
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.
*
......
......@@ -969,6 +969,7 @@ public function getTranslationFromContext(EntityInterface $entity, $langcode = N
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
......
......@@ -117,14 +117,10 @@ public function view(EntityInterface $entity, $view_mode = 'full', $langcode = N
* {@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 @@ public function viewMultiple(array $entities = array(), $view_mode = 'full', $la
$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++;
}
......
......@@ -225,13 +225,13 @@ public function postSave(EntityStorageInterface $storage, $update = TRUE) {
// 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();
}
......
......@@ -246,7 +246,7 @@ public function postSave(EntityStorageInterface $storage, $update = TRUE) {
// 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());
}
}
......
......@@ -194,7 +194,7 @@ public function testBlockViewBuilderAlter() {
// 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 @@ public function testBlockViewBuilderAlter() {
$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');
......
......@@ -71,11 +71,9 @@ protected function getBuildDefaults(EntityInterface $entity, $view_mode, $langco
->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;
......
......@@ -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.
*
......
......@@ -86,7 +86,7 @@ public function testContactLink() {
// 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'));
}
......
......@@ -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 @@ protected function doTestBasicTranslation() {
$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 @@ protected function doTestBasicTranslation() {
], 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));
......
......@@ -267,7 +267,7 @@ public function flush($path = NULL) {
// Clear caches so that formatters may be added for this style.
drupal_theme_rebuild();
Cache::invalidateTags($this->getCacheTags());
Cache::invalidateTags($this->getCacheTagsToInvalidate());
return $this;
}
......
......@@ -17,6 +17,11 @@
*/
class MenuLinkContentTranslationUITest extends ContentTranslationUITestBase {
/**
* {inheritdoc}
*/
protected $defaultCacheContexts = ['languages:language_interface', 'theme', 'user.permissions', 'user.roles:authenticated'];
/**
* Modules to enable.
*
......
......@@ -21,6 +21,21 @@
*/
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.
*
......
......@@ -102,7 +102,7 @@ public function postSave(EntityStorageInterface $storage, $update = TRUE) {
// 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 @@ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
/**
* {@inheritdoc}
*/
public function getCacheTags() {
public function getCacheTagsToInvalidate() {
return $this->shortcut_set->entity->getCacheTags();
}
......
......@@ -18,6 +18,11 @@
*/
class ShortcutTranslationUITest extends ContentTranslationUITestBase {
/**
* {inheritdoc}
*/
protected $defaultCacheContexts = ['languages:language_interface', 'theme', 'user'];
/**
* Modules to enable.
*
......
......@@ -571,7 +571,7 @@ public function testReferencedEntity() {
// 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');
......
......@@ -121,7 +121,7 @@ public function testEntityUri() {
// 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.
......
......@@ -153,7 +153,7 @@ public function cacheGet($type) {
* Clear out cached data for a view.
*/
public function cacheFlush() {
Cache::invalidateTags($this->view->storage->getCacheTags());
Cache::invalidateTags($this->view->storage->getCacheTagsToInvalidate());
}
/**
......
......@@ -197,7 +197,7 @@ public function testTagCaching() {
$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);
......
......@@ -1336,4 +1336,32 @@ public function hasTrustedData() {
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);
}
}
......@@ -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 @@ public function testPostLoad() {
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());
}
}
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