3 namespace Drupal\Tests\system\Functional\Entity;
5 use Drupal\Core\Cache\Cache;
6 use Drupal\Core\Entity\EntityInterface;
7 use Drupal\Core\EventSubscriber\MainContentViewSubscriber;
8 use Drupal\Core\Field\FieldStorageDefinitionInterface;
9 use Drupal\Core\Language\LanguageInterface;
11 use Drupal\field\Entity\FieldStorageConfig;
12 use Drupal\field\Entity\FieldConfig;
13 use Drupal\system\Tests\Cache\PageCacheTagsTestBase;
14 use Drupal\user\Entity\Role;
15 use Drupal\user\RoleInterface;
18 * Provides helper methods for Entity cache tags tests.
20 abstract class EntityCacheTagsTestBase extends PageCacheTagsTestBase {
27 public static $modules = ['entity_test', 'field_test'];
30 * The main entity used for testing.
32 * @var \Drupal\Core\Entity\EntityInterface
37 * The entity instance referencing the main entity.
39 * @var \Drupal\Core\Entity\EntityInterface
41 protected $referencingEntity;
44 * The entity instance not referencing the main entity.
46 * @var \Drupal\Core\Entity\EntityInterface
48 protected $nonReferencingEntity;
53 protected function setUp() {
56 // Give anonymous users permission to view test entities, so that we can
57 // verify the cache tags of cached versions of test entity pages.
58 $user_role = Role::load(RoleInterface::ANONYMOUS_ID);
59 $user_role->grantPermission('view test entity');
63 $this->entity = $this->createEntity();
65 // If this is an entity with field UI enabled, then add a configurable
66 // field. We will use this configurable field in later tests to ensure that
67 // field configuration invalidate render cache entries.
68 if ($this->entity->getEntityType()->get('field_ui_base_route')) {
69 // Add field, so we can modify the field storage and field entities to
70 // verify that changes to those indeed clear cache tags.
71 FieldStorageConfig::create([
72 'field_name' => 'configurable_field',
73 'entity_type' => $this->entity->getEntityTypeId(),
74 'type' => 'test_field',
78 'entity_type' => $this->entity->getEntityTypeId(),
79 'bundle' => $this->entity->bundle(),
80 'field_name' => 'configurable_field',
81 'label' => 'Configurable field',
85 // Reload the entity now that a new field has been added to it.
86 $storage = $this->container
87 ->get('entity.manager')
88 ->getStorage($this->entity->getEntityTypeId());
89 $storage->resetCache();
90 $this->entity = $storage->load($this->entity->id());
93 // Create a referencing and a non-referencing entity.
95 $this->referencingEntity,
96 $this->nonReferencingEntity,
97 ) = $this->createReferenceTestEntities($this->entity);
101 * Generates standardized entity cache tags test info.
103 * @param string $entity_type_label
104 * The label of the entity type whose cache tags to test.
105 * @param string $group
110 * @see \Drupal\simpletest\TestBase::getInfo()
112 protected static function generateStandardizedInfo($entity_type_label, $group) {
114 'name' => "$entity_type_label entity cache tags",
115 'description' => "Test the $entity_type_label entity's cache tags.",
121 * Creates the entity to be tested.
123 * @return \Drupal\Core\Entity\EntityInterface
124 * The entity to be tested.
126 abstract protected function createEntity();
129 * Returns the access cache contexts for the tested entity.
131 * Only list cache contexts that aren't part of the required cache contexts.
133 * @param \Drupal\Core\Entity\EntityInterface $entity
134 * The entity to be tested, as created by createEntity().
137 * An array of the additional cache contexts.
139 * @see \Drupal\Core\Entity\EntityAccessControlHandlerInterface
141 protected function getAccessCacheContextsForEntity(EntityInterface $entity) {
146 * Returns the additional (non-standard) cache contexts for the tested entity.
148 * Only list cache contexts that aren't part of the required cache contexts.
150 * @param \Drupal\Core\Entity\EntityInterface $entity
151 * The entity to be tested, as created by createEntity().
154 * An array of the additional cache contexts.
156 * @see \Drupal\system\Tests\Entity\EntityCacheTagsTestBase::createEntity()
158 protected function getAdditionalCacheContextsForEntity(EntityInterface $entity) {
163 * Returns the additional (non-standard) cache tags for the tested entity.
165 * @param \Drupal\Core\Entity\EntityInterface $entity
166 * The entity to be tested, as created by createEntity().
168 * An array of the additional cache tags.
170 * @see \Drupal\system\Tests\Entity\EntityCacheTagsTestBase::createEntity()
172 protected function getAdditionalCacheTagsForEntity(EntityInterface $entity) {
177 * Returns the additional cache tags for the tested entity's listing by type.
180 * An array of the additional cache contexts.
182 protected function getAdditionalCacheContextsForEntityListing() {
187 * Returns the additional cache tags for the tested entity's listing by type.
189 * Necessary when there are unavoidable default entities of this type, e.g.
190 * the anonymous and administrator User entities always exist.
193 * An array of the additional cache tags.
195 protected function getAdditionalCacheTagsForEntityListing() {
200 * Selects the preferred view mode for the given entity type.
202 * Prefers 'full', picks the first one otherwise, and if none are available,
205 protected function selectViewMode($entity_type) {
206 $view_modes = \Drupal::entityManager()
207 ->getStorage('entity_view_mode')
208 ->loadByProperties(['targetEntityType' => $entity_type]);
210 if (empty($view_modes)) {
214 // Prefer the "full" display mode.
215 if (isset($view_modes[$entity_type . '.full'])) {
219 $view_modes = array_keys($view_modes);
220 return substr($view_modes[0], strlen($entity_type) + 1);
226 * Creates a referencing and a non-referencing entity for testing purposes.
228 * @param \Drupal\Core\Entity\EntityInterface $referenced_entity
229 * The entity that the referencing entity should reference.
231 * @return \Drupal\Core\Entity\EntityInterface[]
232 * An array containing a referencing entity and a non-referencing entity.
234 protected function createReferenceTestEntities($referenced_entity) {
235 // All referencing entities should be of the type 'entity_test'.
236 $entity_type = 'entity_test';
238 // Create a "foo" bundle for the given entity type.
240 entity_test_create_bundle($bundle, NULL, $entity_type);
242 // Add a field of the given type to the given entity type's "foo" bundle.
243 $field_name = $referenced_entity->getEntityTypeId() . '_reference';
244 FieldStorageConfig::create([
245 'field_name' => $field_name,
246 'entity_type' => $entity_type,
247 'type' => 'entity_reference',
248 'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
250 'target_type' => $referenced_entity->getEntityTypeId(),
253 FieldConfig::create([
254 'field_name' => $field_name,
255 'entity_type' => $entity_type,
258 'handler' => 'default',
259 'handler_settings' => [
260 'target_bundles' => [
261 $referenced_entity->bundle() => $referenced_entity->bundle(),
263 'sort' => ['field' => '_none'],
264 'auto_create' => FALSE,
268 if (!$this->entity->getEntityType()->hasHandlerClass('view_builder')) {
269 entity_get_display($entity_type, $bundle, 'full')
270 ->setComponent($field_name, [
271 'type' => 'entity_reference_label',
276 $referenced_entity_view_mode = $this->selectViewMode($this->entity->getEntityTypeId());
277 entity_get_display($entity_type, $bundle, 'full')
278 ->setComponent($field_name, [
279 'type' => 'entity_reference_entity_view',
281 'view_mode' => $referenced_entity_view_mode,
287 // Create an entity that does reference the entity being tested.
288 $label_key = \Drupal::entityManager()->getDefinition($entity_type)->getKey('label');
289 $referencing_entity = $this->container->get('entity_type.manager')
290 ->getStorage($entity_type)
292 $label_key => 'Referencing ' . $entity_type,
295 $field_name => ['target_id' => $referenced_entity->id()],
297 $referencing_entity->save();
299 // Create an entity that does not reference the entity being tested.
300 $non_referencing_entity = $this->container->get('entity_type.manager')
301 ->getStorage($entity_type)
303 $label_key => 'Non-referencing ' . $entity_type,
307 $non_referencing_entity->save();
311 $non_referencing_entity,
316 * Tests cache tags presence and invalidation of the entity when referenced.
318 * Tests the following cache tags:
319 * - entity type view cache tag: "<entity type>_view"
320 * - entity cache tag: "<entity type>:<entity ID>"
321 * - entity type list cache tag: "<entity type>_list"
322 * - referencing entity type view cache tag: "<referencing entity type>_view"
323 * - referencing entity type cache tag: "<referencing entity type>:<referencing entity ID>"
325 public function testReferencedEntity() {
326 $entity_type = $this->entity->getEntityTypeId();
327 $referencing_entity_url = $this->referencingEntity->urlInfo('canonical');
328 $non_referencing_entity_url = $this->nonReferencingEntity->urlInfo('canonical');
329 $listing_url = Url::fromRoute('entity.entity_test.collection_referencing_entities', [
330 'entity_reference_field_name' => $entity_type . '_reference',
331 'referenced_entity_type' => $entity_type,
332 'referenced_entity_id' => $this->entity->id(),
334 $empty_entity_listing_url = Url::fromRoute('entity.entity_test.collection_empty', ['entity_type_id' => $entity_type]);
335 $nonempty_entity_listing_url = Url::fromRoute('entity.entity_test.collection_labels_alphabetically', ['entity_type_id' => $entity_type]);
337 // The default cache contexts for rendered entities.
338 $default_cache_contexts = ['languages:' . LanguageInterface::TYPE_INTERFACE, 'theme', 'user.permissions'];
339 $entity_cache_contexts = $default_cache_contexts;
340 $page_cache_contexts = Cache::mergeContexts($default_cache_contexts, ['url.query_args:' . MainContentViewSubscriber::WRAPPER_FORMAT]);
342 // Cache tags present on every rendered page.
343 // 'user.permissions' is a required cache context, and responses that vary
344 // by this cache context when requested by anonymous users automatically
345 // also get this cache tag, to ensure correct invalidation.
346 $page_cache_tags = Cache::mergeTags(['http_response', 'rendered'], ['config:user.role.anonymous']);
347 // If the block module is used, the Block page display variant is used,
348 // which adds the block config entity type's list cache tags.
349 $page_cache_tags = Cache::mergeTags($page_cache_tags, \Drupal::moduleHandler()->moduleExists('block') ? ['config:block_list'] : []);
351 $page_cache_tags_referencing_entity = in_array('user.permissions', $this->getAccessCacheContextsForEntity($this->referencingEntity)) ? ['config:user.role.anonymous'] : [];
353 $view_cache_tag = [];
354 if ($this->entity->getEntityType()->hasHandlerClass('view_builder')) {
355 $view_cache_tag = \Drupal::entityManager()->getViewBuilder($entity_type)
359 $context_metadata = \Drupal::service('cache_contexts_manager')->convertTokensToKeys($entity_cache_contexts);
360 $cache_context_tags = $context_metadata->getCacheTags();
362 // Generate the cache tags for the (non) referencing entities.
363 $referencing_entity_cache_tags = Cache::mergeTags($this->referencingEntity->getCacheTags(), \Drupal::entityManager()->getViewBuilder('entity_test')->getCacheTags());
364 // Includes the main entity's cache tags, since this entity references it.
365 $referencing_entity_cache_tags = Cache::mergeTags($referencing_entity_cache_tags, $this->entity->getCacheTags());
366 $referencing_entity_cache_tags = Cache::mergeTags($referencing_entity_cache_tags, $this->getAdditionalCacheTagsForEntity($this->entity));
367 $referencing_entity_cache_tags = Cache::mergeTags($referencing_entity_cache_tags, $view_cache_tag);
368 $referencing_entity_cache_tags = Cache::mergeTags($referencing_entity_cache_tags, $cache_context_tags);
369 $referencing_entity_cache_tags = Cache::mergeTags($referencing_entity_cache_tags, ['rendered']);
371 $non_referencing_entity_cache_tags = Cache::mergeTags($this->nonReferencingEntity->getCacheTags(), \Drupal::entityManager()->getViewBuilder('entity_test')->getCacheTags());
372 $non_referencing_entity_cache_tags = Cache::mergeTags($non_referencing_entity_cache_tags, ['rendered']);
374 // Generate the cache tags for all two possible entity listing paths.
375 // 1. list cache tag only (listing query has no match)
376 // 2. list cache tag plus entity cache tag (listing query has a match)
377 $empty_entity_listing_cache_tags = Cache::mergeTags($this->entity->getEntityType()->getListCacheTags(), $page_cache_tags);
379 $nonempty_entity_listing_cache_tags = Cache::mergeTags($this->entity->getEntityType()->getListCacheTags(), $this->entity->getCacheTags());
380 $nonempty_entity_listing_cache_tags = Cache::mergeTags($nonempty_entity_listing_cache_tags, $this->getAdditionalCacheTagsForEntityListing($this->entity));
381 $nonempty_entity_listing_cache_tags = Cache::mergeTags($nonempty_entity_listing_cache_tags, $page_cache_tags);
383 $this->pass("Test referencing entity.", 'Debug');
384 $this->verifyPageCache($referencing_entity_url, 'MISS');
386 // Verify a cache hit, but also the presence of the correct cache tags.
387 $expected_tags = Cache::mergeTags($referencing_entity_cache_tags, $page_cache_tags);
388 $expected_tags = Cache::mergeTags($expected_tags, $page_cache_tags_referencing_entity);
389 $this->verifyPageCache($referencing_entity_url, 'HIT', $expected_tags);
391 // Also verify the existence of an entity render cache entry.
392 $cache_keys = ['entity_view', 'entity_test', $this->referencingEntity->id(), 'full'];
393 $cid = $this->createCacheId($cache_keys, $entity_cache_contexts);
394 $access_cache_contexts = $this->getAccessCacheContextsForEntity($this->entity);
395 $additional_cache_contexts = $this->getAdditionalCacheContextsForEntity($this->referencingEntity);
396 $redirected_cid = NULL;
397 if (count($access_cache_contexts) || count($additional_cache_contexts)) {
398 $cache_contexts = Cache::mergeContexts($entity_cache_contexts, $additional_cache_contexts);
399 $cache_contexts = Cache::mergeContexts($cache_contexts, $access_cache_contexts);
400 $redirected_cid = $this->createCacheId($cache_keys, $cache_contexts);
401 $context_metadata = \Drupal::service('cache_contexts_manager')->convertTokensToKeys($cache_contexts);
402 $referencing_entity_cache_tags = Cache::mergeTags($referencing_entity_cache_tags, $context_metadata->getCacheTags());
404 $this->verifyRenderCache($cid, $referencing_entity_cache_tags, $redirected_cid);
406 $this->pass("Test non-referencing entity.", 'Debug');
407 $this->verifyPageCache($non_referencing_entity_url, 'MISS');
408 // Verify a cache hit, but also the presence of the correct cache tags.
409 $this->verifyPageCache($non_referencing_entity_url, 'HIT', Cache::mergeTags($non_referencing_entity_cache_tags, $page_cache_tags));
410 // Also verify the existence of an entity render cache entry.
411 $cache_keys = ['entity_view', 'entity_test', $this->nonReferencingEntity->id(), 'full'];
412 $cid = $this->createCacheId($cache_keys, $entity_cache_contexts);
413 $this->verifyRenderCache($cid, $non_referencing_entity_cache_tags);
416 $this->pass("Test listing of referencing entities.", 'Debug');
417 // Prime the page cache for the listing of referencing entities.
418 $this->verifyPageCache($listing_url, 'MISS');
420 // Verify a cache hit, but also the presence of the correct cache tags.
421 $expected_tags = Cache::mergeTags($referencing_entity_cache_tags, $page_cache_tags);
422 $expected_tags = Cache::mergeTags($expected_tags, $page_cache_tags_referencing_entity);
423 $this->verifyPageCache($listing_url, 'HIT', $expected_tags);
425 $this->pass("Test empty listing.", 'Debug');
426 // Prime the page cache for the empty listing.
427 $this->verifyPageCache($empty_entity_listing_url, 'MISS');
428 // Verify a cache hit, but also the presence of the correct cache tags.
429 $this->verifyPageCache($empty_entity_listing_url, 'HIT', $empty_entity_listing_cache_tags);
430 // Verify the entity type's list cache contexts are present.
431 $contexts_in_header = $this->drupalGetHeader('X-Drupal-Cache-Contexts');
432 $this->assertEqual(Cache::mergeContexts($page_cache_contexts, $this->getAdditionalCacheContextsForEntityListing()), empty($contexts_in_header) ? [] : explode(' ', $contexts_in_header));
435 $this->pass("Test listing containing referenced entity.", 'Debug');
436 // Prime the page cache for the listing containing the referenced entity.
437 $this->verifyPageCache($nonempty_entity_listing_url, 'MISS', $nonempty_entity_listing_cache_tags);
438 // Verify a cache hit, but also the presence of the correct cache tags.
439 $this->verifyPageCache($nonempty_entity_listing_url, 'HIT', $nonempty_entity_listing_cache_tags);
440 // Verify the entity type's list cache contexts are present.
441 $contexts_in_header = $this->drupalGetHeader('X-Drupal-Cache-Contexts');
442 $this->assertEqual(Cache::mergeContexts($page_cache_contexts, $this->getAdditionalCacheContextsForEntityListing()), empty($contexts_in_header) ? [] : explode(' ', $contexts_in_header));
445 // Verify that after modifying the referenced entity, there is a cache miss
446 // for every route except the one for the non-referencing entity.
447 $this->pass("Test modification of referenced entity.", 'Debug');
448 $this->entity->save();
449 $this->verifyPageCache($referencing_entity_url, 'MISS');
450 $this->verifyPageCache($listing_url, 'MISS');
451 $this->verifyPageCache($empty_entity_listing_url, 'MISS');
452 $this->verifyPageCache($nonempty_entity_listing_url, 'MISS');
453 $this->verifyPageCache($non_referencing_entity_url, 'HIT');
455 // Verify cache hits.
456 $this->verifyPageCache($referencing_entity_url, 'HIT');
457 $this->verifyPageCache($listing_url, 'HIT');
458 $this->verifyPageCache($empty_entity_listing_url, 'HIT');
459 $this->verifyPageCache($nonempty_entity_listing_url, 'HIT');
462 // Verify that after modifying the referencing entity, there is a cache miss
463 // for every route except the ones for the non-referencing entity and the
464 // empty entity listing.
465 $this->pass("Test modification of referencing entity.", 'Debug');
466 $this->referencingEntity->save();
467 $this->verifyPageCache($referencing_entity_url, 'MISS');
468 $this->verifyPageCache($listing_url, 'MISS');
469 $this->verifyPageCache($nonempty_entity_listing_url, 'HIT');
470 $this->verifyPageCache($non_referencing_entity_url, 'HIT');
471 $this->verifyPageCache($empty_entity_listing_url, 'HIT');
473 // Verify cache hits.
474 $this->verifyPageCache($referencing_entity_url, 'HIT');
475 $this->verifyPageCache($listing_url, 'HIT');
476 $this->verifyPageCache($nonempty_entity_listing_url, 'HIT');
479 // Verify that after modifying the non-referencing entity, there is a cache
480 // miss only for the non-referencing entity route.
481 $this->pass("Test modification of non-referencing entity.", 'Debug');
482 $this->nonReferencingEntity->save();
483 $this->verifyPageCache($referencing_entity_url, 'HIT');
484 $this->verifyPageCache($listing_url, 'HIT');
485 $this->verifyPageCache($empty_entity_listing_url, 'HIT');
486 $this->verifyPageCache($nonempty_entity_listing_url, 'HIT');
487 $this->verifyPageCache($non_referencing_entity_url, 'MISS');
489 // Verify cache hits.
490 $this->verifyPageCache($non_referencing_entity_url, 'HIT');
493 if ($this->entity->getEntityType()->hasHandlerClass('view_builder')) {
494 // Verify that after modifying the entity's display, there is a cache miss
495 // for both the referencing entity, and the listing of referencing
496 // entities, but not for any other routes.
497 $referenced_entity_view_mode = $this->selectViewMode($this->entity->getEntityTypeId());
498 $this->pass("Test modification of referenced entity's '$referenced_entity_view_mode' display.", 'Debug');
499 $entity_display = entity_get_display($entity_type, $this->entity->bundle(), $referenced_entity_view_mode);
500 $entity_display->save();
501 $this->verifyPageCache($referencing_entity_url, 'MISS');
502 $this->verifyPageCache($listing_url, 'MISS');
503 $this->verifyPageCache($non_referencing_entity_url, 'HIT');
504 $this->verifyPageCache($empty_entity_listing_url, 'HIT');
505 $this->verifyPageCache($nonempty_entity_listing_url, 'HIT');
507 // Verify cache hits.
508 $this->verifyPageCache($referencing_entity_url, 'HIT');
509 $this->verifyPageCache($listing_url, 'HIT');
513 if ($bundle_entity_type_id = $this->entity->getEntityType()->getBundleEntityType()) {
514 // Verify that after modifying the corresponding bundle entity, there is a
515 // cache miss for both the referencing entity, and the listing of
516 // referencing entities, but not for any other routes.
517 $this->pass("Test modification of referenced entity's bundle entity.", 'Debug');
518 $bundle_entity = $this->container->get('entity_type.manager')
519 ->getStorage($bundle_entity_type_id)
520 ->load($this->entity->bundle());
521 $bundle_entity->save();
522 $this->verifyPageCache($referencing_entity_url, 'MISS');
523 $this->verifyPageCache($listing_url, 'MISS');
524 $this->verifyPageCache($non_referencing_entity_url, 'HIT');
525 // Special case: entity types may choose to use their bundle entity type
526 // cache tags, to avoid having excessively granular invalidation.
527 $is_special_case = $bundle_entity->getCacheTags() == $this->entity->getCacheTags() && $bundle_entity->getEntityType()->getListCacheTags() == $this->entity->getEntityType()->getListCacheTags();
528 if ($is_special_case) {
529 $this->verifyPageCache($empty_entity_listing_url, 'MISS');
530 $this->verifyPageCache($nonempty_entity_listing_url, 'MISS');
533 $this->verifyPageCache($empty_entity_listing_url, 'HIT');
534 $this->verifyPageCache($nonempty_entity_listing_url, 'HIT');
537 // Verify cache hits.
538 $this->verifyPageCache($referencing_entity_url, 'HIT');
539 $this->verifyPageCache($listing_url, 'HIT');
540 if ($is_special_case) {
541 $this->verifyPageCache($empty_entity_listing_url, 'HIT');
542 $this->verifyPageCache($nonempty_entity_listing_url, 'HIT');
547 if ($this->entity->getEntityType()->get('field_ui_base_route')) {
548 // Verify that after modifying a configurable field on the entity, there
550 $this->pass("Test modification of referenced entity's configurable field.", 'Debug');
551 $field_storage_name = $this->entity->getEntityTypeId() . '.configurable_field';
552 $field_storage = FieldStorageConfig::load($field_storage_name);
553 $field_storage->save();
554 $this->verifyPageCache($referencing_entity_url, 'MISS');
555 $this->verifyPageCache($listing_url, 'MISS');
556 $this->verifyPageCache($empty_entity_listing_url, 'HIT');
557 $this->verifyPageCache($nonempty_entity_listing_url, 'HIT');
558 $this->verifyPageCache($non_referencing_entity_url, 'HIT');
560 // Verify cache hits.
561 $this->verifyPageCache($referencing_entity_url, 'HIT');
562 $this->verifyPageCache($listing_url, 'HIT');
565 // Verify that after modifying a configurable field on the entity, there
567 $this->pass("Test modification of referenced entity's configurable field.", 'Debug');
568 $field_name = $this->entity->getEntityTypeId() . '.' . $this->entity->bundle() . '.configurable_field';
569 $field = FieldConfig::load($field_name);
571 $this->verifyPageCache($referencing_entity_url, 'MISS');
572 $this->verifyPageCache($listing_url, 'MISS');
573 $this->verifyPageCache($empty_entity_listing_url, 'HIT');
574 $this->verifyPageCache($nonempty_entity_listing_url, 'HIT');
575 $this->verifyPageCache($non_referencing_entity_url, 'HIT');
577 // Verify cache hits.
578 $this->verifyPageCache($referencing_entity_url, 'HIT');
579 $this->verifyPageCache($listing_url, 'HIT');
583 // Verify that after invalidating the entity's cache tag directly, there is
584 // a cache miss for every route except the ones for the non-referencing
585 // entity and the empty entity listing.
586 $this->pass("Test invalidation of referenced entity's cache tag.", 'Debug');
587 Cache::invalidateTags($this->entity->getCacheTagsToInvalidate());
588 $this->verifyPageCache($referencing_entity_url, 'MISS');
589 $this->verifyPageCache($listing_url, 'MISS');
590 $this->verifyPageCache($nonempty_entity_listing_url, 'MISS');
591 $this->verifyPageCache($non_referencing_entity_url, 'HIT');
592 $this->verifyPageCache($empty_entity_listing_url, 'HIT');
594 // Verify cache hits.
595 $this->verifyPageCache($referencing_entity_url, 'HIT');
596 $this->verifyPageCache($listing_url, 'HIT');
597 $this->verifyPageCache($nonempty_entity_listing_url, 'HIT');
599 // Verify that after invalidating the entity's list cache tag directly,
600 // there is a cache miss for both the empty entity listing and the non-empty
601 // entity listing routes, but not for other routes.
602 $this->pass("Test invalidation of referenced entity's list cache tag.", 'Debug');
603 Cache::invalidateTags($this->entity->getEntityType()->getListCacheTags());
604 $this->verifyPageCache($empty_entity_listing_url, 'MISS');
605 $this->verifyPageCache($nonempty_entity_listing_url, 'MISS');
606 $this->verifyPageCache($referencing_entity_url, 'HIT');
607 $this->verifyPageCache($non_referencing_entity_url, 'HIT');
608 $this->verifyPageCache($listing_url, 'HIT');
610 // Verify cache hits.
611 $this->verifyPageCache($empty_entity_listing_url, 'HIT');
612 $this->verifyPageCache($nonempty_entity_listing_url, 'HIT');
615 if (!empty($view_cache_tag)) {
616 // Verify that after invalidating the generic entity type's view cache tag
617 // directly, there is a cache miss for both the referencing entity, and the
618 // listing of referencing entities, but not for other routes.
619 $this->pass("Test invalidation of referenced entity's 'view' cache tag.", 'Debug');
620 Cache::invalidateTags($view_cache_tag);
621 $this->verifyPageCache($referencing_entity_url, 'MISS');
622 $this->verifyPageCache($listing_url, 'MISS');
623 $this->verifyPageCache($non_referencing_entity_url, 'HIT');
624 $this->verifyPageCache($empty_entity_listing_url, 'HIT');
625 $this->verifyPageCache($nonempty_entity_listing_url, 'HIT');
627 // Verify cache hits.
628 $this->verifyPageCache($referencing_entity_url, 'HIT');
629 $this->verifyPageCache($listing_url, 'HIT');
632 // Verify that after deleting the entity, there is a cache miss for every
633 // route except for the non-referencing entity one.
634 $this->pass('Test deletion of referenced entity.', 'Debug');
635 $this->entity->delete();
636 $this->verifyPageCache($referencing_entity_url, 'MISS');
637 $this->verifyPageCache($listing_url, 'MISS');
638 $this->verifyPageCache($empty_entity_listing_url, 'MISS');
639 $this->verifyPageCache($nonempty_entity_listing_url, 'MISS');
640 $this->verifyPageCache($non_referencing_entity_url, 'HIT');
642 // Verify cache hits.
643 $referencing_entity_cache_tags = Cache::mergeTags($this->referencingEntity->getCacheTags(), \Drupal::entityManager()->getViewBuilder('entity_test')->getCacheTags());
644 $referencing_entity_cache_tags = Cache::mergeTags($referencing_entity_cache_tags, ['http_response', 'rendered']);
646 $nonempty_entity_listing_cache_tags = Cache::mergeTags($this->entity->getEntityType()->getListCacheTags(), $this->getAdditionalCacheTagsForEntityListing());
647 $nonempty_entity_listing_cache_tags = Cache::mergeTags($nonempty_entity_listing_cache_tags, $page_cache_tags);
649 $this->verifyPageCache($referencing_entity_url, 'HIT', Cache::mergeTags($referencing_entity_cache_tags, $page_cache_tags));
650 $this->verifyPageCache($listing_url, 'HIT', $page_cache_tags);
651 $this->verifyPageCache($empty_entity_listing_url, 'HIT', $empty_entity_listing_cache_tags);
652 $this->verifyPageCache($nonempty_entity_listing_url, 'HIT', $nonempty_entity_listing_cache_tags);
656 * Creates a cache ID from a list of cache keys and a set of cache contexts.
658 * @param string[] $keys
659 * A list of cache keys.
660 * @param string[] $contexts
661 * A set of cache contexts.
664 * The cache ID string.
666 protected function createCacheId(array $keys, array $contexts) {
669 $contexts = \Drupal::service('cache_contexts_manager')->convertTokensToKeys($contexts);
670 $cid_parts = array_merge($cid_parts, $contexts->getKeys());
672 return implode(':', $cid_parts);
676 * Verify that a given render cache entry exists, with the correct cache tags.
679 * The render cache item ID.
681 * An array of expected cache tags.
682 * @param string|null $redirected_cid
683 * (optional) The redirected render cache item ID.
685 protected function verifyRenderCache($cid, array $tags, $redirected_cid = NULL) {
686 // Also verify the existence of an entity render cache entry.
687 $cache_entry = \Drupal::cache('render')->get($cid);
688 $this->assertTrue($cache_entry, 'A render cache entry exists.');
689 sort($cache_entry->tags);
691 $this->assertIdentical($cache_entry->tags, $tags);
692 $is_redirecting_cache_item = isset($cache_entry->data['#cache_redirect']);
693 if ($redirected_cid === NULL) {
694 $this->assertFalse($is_redirecting_cache_item, 'Render cache entry is not a redirect.');
695 // If this is a redirecting cache item unlike we expected, log it.
696 if ($is_redirecting_cache_item) {
697 debug($cache_entry->data);
701 // Verify that $cid contains a cache redirect.
702 $this->assertTrue($is_redirecting_cache_item, 'Render cache entry is a redirect.');
703 // If this is not a redirecting cache item unlike we expected, log it.
704 if (!$is_redirecting_cache_item) {
705 debug($cache_entry->data);
707 // Verify that the cache redirect points to the expected CID.
708 $redirect_cache_metadata = $cache_entry->data['#cache'];
709 $actual_redirection_cid = $this->createCacheId(
710 $redirect_cache_metadata['keys'],
711 $redirect_cache_metadata['contexts']
713 $this->assertIdentical($redirected_cid, $actual_redirection_cid);
714 // Finally, verify that the redirected CID exists and has the same cache
716 $this->verifyRenderCache($redirected_cid, $tags);