EntityCacheTagsTestBase.php 19.7 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains \Drupal\system\Tests\Entity\EntityCacheTagsTestBase.
 */

namespace Drupal\system\Tests\Entity;

10
use Drupal\Component\Utility\NestedArray;
11
use Drupal\Core\Cache\Cache;
12
use Drupal\Core\Entity\EntityInterface;
13
use Drupal\Core\EventSubscriber\HtmlViewSubscriber;
14
use Drupal\Core\Field\FieldStorageDefinitionInterface;
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
use Drupal\system\Tests\Cache\PageCacheTagsTestBase;

/**
 * Provides helper methods for Entity cache tags tests.
 */
abstract class EntityCacheTagsTestBase extends PageCacheTagsTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = array('entity_reference', 'entity_test', 'field_test');

  /**
   * The main entity used for testing.
   *
   * @var \Drupal\Core\Entity\EntityInterface
   */
  protected $entity;

  /**
   * The entity instance referencing the main entity.
   *
   * @var \Drupal\Core\Entity\EntityInterface
   */
  protected $referencing_entity;

  /**
   * The entity instance not referencing the main entity.
   *
   * @var \Drupal\Core\Entity\EntityInterface
   */
  protected $non_referencing_entity;

  /**
   * {@inheritdoc}
   */
  public function setUp() {
    parent::setUp();

    // Give anonymous users permission to view test entities, so that we can
    // verify the cache tags of cached versions of test entity pages.
    $user_role = entity_load('user_role', DRUPAL_ANONYMOUS_RID);
    $user_role->grantPermission('view test entity');
    $user_role->save();

    // Create an entity.
    $this->entity = $this->createEntity();

    // If this is a fieldable entity, then add a configurable field. We will use
    // this configurable field in later tests to ensure that modifications to
    // field (instance) configuration invalidate render cache entries.
    if ($this->entity->getEntityType()->isFieldable()) {
      // Add field, so we can modify the Field and FieldInstance entities to
      // verify that changes to those indeed clear cache tags.
      entity_create('field_config', array(
        'name' => 'configurable_field',
        'entity_type' => $this->entity->getEntityTypeId(),
        'type' => 'test_field',
        'settings' => array(),
      ))->save();
      entity_create('field_instance_config', array(
        'entity_type' => $this->entity->getEntityTypeId(),
        'bundle' => $this->entity->bundle(),
        'field_name' => 'configurable_field',
        'label' => 'Configurable field',
        'settings' => array(),
      ))->save();

      // Reload the entity now that a new field has been added to it.
86
      $storage = $this->container
87
        ->get('entity.manager')
88 89 90
        ->getStorage($this->entity->getEntityTypeId());
      $storage->resetCache();
      $this->entity = $storage->load($this->entity->id());
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
    }

    // Create a referencing and a non-referencing entity.
    list(
      $this->referencing_entity,
      $this->non_referencing_entity,
    ) = $this->createReferenceTestEntities($this->entity);
  }

  /**
   * Generates standardized entity cache tags test info.
   *
   * @param string $entity_type_label
   *   The label of the entity type whose cache tags to test.
   * @param string $group
   *   The test group.
   *
   * @return array
   *
   * @see \Drupal\simpletest\TestBase::getInfo()
   */
  protected static function generateStandardizedInfo($entity_type_label, $group) {
    return array(
      'name' => "$entity_type_label entity cache tags",
      'description' => "Test the $entity_type_label entity's cache tags.",
      'group' => $group,
    );
  }

  /**
   * Creates the entity to be tested.
   *
   * @return \Drupal\Core\Entity\EntityInterface
   *   The entity to be tested.
   */
  abstract protected function createEntity();

128 129 130 131 132 133 134 135 136 137 138 139 140 141
  /**
   * Returns the additional (non-standard) cache tags for the tested entity.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity to be tested, as created by createEntity().
   * @return array
   *   An array of the additional cache tags.
   *
   * @see \Drupal\system\Tests\Entity\EntityCacheTagsTestBase::createEntity()
   */
  protected function getAdditionalCacheTagsForEntity(EntityInterface $entity) {
    return array();
  }

142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
  /**
   * Selects the preferred view mode for the given entity type.
   *
   * Prefers 'full', picks the first one otherwise, and if none are available,
   * chooses 'default'.
   */
  protected function selectViewMode($entity_type) {
    $view_modes = \Drupal::entityManager()
      ->getStorage('view_mode')
      ->loadByProperties(array('targetEntityType' => $entity_type));

    if (empty($view_modes)) {
      return 'default';
    }
    else {
      // Prefer the "full" display mode.
      if (isset($view_modes[$entity_type . '.full'])) {
        return 'full';
      }
      else {
        $view_modes = array_keys($view_modes);
        return substr($view_modes[0], strlen($entity_type) + 1);
      }
    }
  }

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
  /**
   * Creates a referencing and a non-referencing entity for testing purposes.
   *
   * @param \Drupal\Core\Entity\EntityInterface $referenced_entity
   *  The entity that the referencing entity should reference.
   *
   * @return \Drupal\Core\Entity\EntityInterface[]
   *  An array containing a referencing entity and a non-referencing entity.
   */
  protected function createReferenceTestEntities($referenced_entity) {
    // All referencing entities should be of the type 'entity_test'.
    $entity_type = 'entity_test';

    // Create a "foo" bundle for the given entity type.
    $bundle = 'foo';
    entity_test_create_bundle($bundle, NULL, $entity_type);

    // Add a field of the given type to the given entity type's "foo" bundle.
    $field_name = $referenced_entity->getEntityTypeId() . '_reference';
    entity_create('field_config', array(
      'name' => $field_name,
      'entity_type' => $entity_type,
      'type' => 'entity_reference',
191
      'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
      'settings' => array(
        'target_type' => $referenced_entity->getEntityTypeId(),
      ),
    ))->save();
    entity_create('field_instance_config', array(
      'field_name' => $field_name,
      'entity_type' => $entity_type,
      'bundle' => $bundle,
      'settings' => array(
        'handler' => 'default',
        'handler_settings' => array(
          'target_bundles' => array(
            $referenced_entity->bundle() => $referenced_entity->bundle(),
          ),
          'sort' => array('field' => '_none'),
          'auto_create' => FALSE,
        ),
      ),
    ))->save();
211
    if (!$this->entity->getEntityType()->hasControllerClass('view_builder')) {
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
      entity_get_display($entity_type, $bundle, 'full')
        ->setComponent($field_name, array(
          'type' => 'entity_reference_label',
        ))
        ->save();
    }
    else {
      $referenced_entity_view_mode = $this->selectViewMode($this->entity->getEntityTypeId());
      entity_get_display($entity_type, $bundle, 'full')
        ->setComponent($field_name, array(
          'type' => 'entity_reference_entity_view',
          'settings' => array(
            'view_mode' => $referenced_entity_view_mode,
          ),
        ))
        ->save();
228
    }
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268

    // Create an entity that does reference the entity being tested.
    $label_key = \Drupal::entityManager()->getDefinition($entity_type)->getKey('label');
    $referencing_entity = entity_create($entity_type, array(
      $label_key => 'Referencing ' . $entity_type,
      'status' => 1,
      'type' => $bundle,
      $field_name => array('target_id' => $referenced_entity->id()),
    ));
    $referencing_entity->save();

    // Create an entity that does not reference the entity being tested.
    $non_referencing_entity = entity_create($entity_type, array(
      $label_key => 'Non-referencing ' . $entity_type,
      'status' => 1,
      'type' => $bundle,
    ));
    $non_referencing_entity->save();

    return array(
      $referencing_entity,
      $non_referencing_entity,
    );
  }

  /**
   * Tests cache tags presence and invalidation of the entity when referenced.
   *
   * Tests the following cache tags:
   * - "<entity type>_view:1"
   * - "<entity type>:<entity ID>"
   * - "<referencing entity type>_view:1"
   * * - "<referencing entity type>:<referencing entity ID>"
   */
  public function testReferencedEntity() {
    $entity_type = $this->entity->getEntityTypeId();
    $referencing_entity_path = $this->referencing_entity->getSystemPath();
    $non_referencing_entity_path = $this->non_referencing_entity->getSystemPath();
    $listing_path = 'entity_test/list/' . $entity_type . '_reference/' . $entity_type . '/' . $this->entity->id();

269 270
    $render_cache_tags = array('rendered:1');
    $theme_cache_tags = array('theme:stark', 'theme_global_settings:1');
271

272 273 274 275 276
    $view_cache_tag = array();
    if ($this->entity->getEntityType()->hasControllerClass('view_builder')) {
      $view_cache_tag = \Drupal::entityManager()->getViewBuilder($entity_type)
        ->getCacheTag();
    }
277 278

    // Generate the cache tags for the (non) referencing entities.
279 280 281
    $referencing_entity_cache_tags = NestedArray::mergeDeep(
      $this->referencing_entity->getCacheTag(),
      \Drupal::entityManager()->getViewBuilder('entity_test')->getCacheTag(),
282
      // Includes the main entity's cache tags, since this entity references it.
283 284
      $this->entity->getCacheTag(),
      $view_cache_tag
285
    );
286
    $referencing_entity_cache_tags = explode(' ', HtmlViewSubscriber::convertCacheTagsToHeader($referencing_entity_cache_tags));
287
    $referencing_entity_cache_tags = array_merge($referencing_entity_cache_tags, $this->getAdditionalCacheTagsForEntity($this->entity));
288 289 290
    $non_referencing_entity_cache_tags = NestedArray::mergeDeep(
      $this->non_referencing_entity->getCacheTag(),
      \Drupal::entityManager()->getViewBuilder('entity_test')->getCacheTag()
291
    );
292
    $non_referencing_entity_cache_tags = explode(' ', HtmlViewSubscriber::convertCacheTagsToHeader($non_referencing_entity_cache_tags));
293 294


295
    $this->pass("Test referencing entity.", 'Debug');
296 297
    $this->verifyPageCache($referencing_entity_path, 'MISS');
    // Verify a cache hit, but also the presence of the correct cache tags.
298
    $tags = array_merge($render_cache_tags, $theme_cache_tags, $referencing_entity_cache_tags);
299 300
    $this->verifyPageCache($referencing_entity_path, 'HIT', $tags);
    // Also verify the existence of an entity render cache entry.
301
    $cid = 'entity_view:entity_test:' . $this->referencing_entity->id() . ':full:stark:r.anonymous:' . date_default_timezone_get();
302 303
    $tags = array_merge($render_cache_tags, $referencing_entity_cache_tags);
    $this->verifyRenderCache($cid, $tags);
304

305
    $this->pass("Test non-referencing entity.", 'Debug');
306 307
    $this->verifyPageCache($non_referencing_entity_path, 'MISS');
    // Verify a cache hit, but also the presence of the correct cache tags.
308
    $tags = array_merge($render_cache_tags, $theme_cache_tags, $non_referencing_entity_cache_tags);
309 310
    $this->verifyPageCache($non_referencing_entity_path, 'HIT', $tags);
    // Also verify the existence of an entity render cache entry.
311
    $cid = 'entity_view:entity_test:' . $this->non_referencing_entity->id() . ':full:stark:r.anonymous:' . date_default_timezone_get();
312 313
    $tags = array_merge($render_cache_tags, $non_referencing_entity_cache_tags);
    $this->verifyRenderCache($cid, $tags);
314 315


316
    $this->pass("Test listing of referencing entities.", 'Debug');
317 318 319
    // Prime the page cache for the listing of referencing entities.
    $this->verifyPageCache($listing_path, 'MISS');
    // Verify a cache hit, but also the presence of the correct cache tags.
320
    $tags = array_merge($render_cache_tags, $theme_cache_tags, $referencing_entity_cache_tags);
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
    $this->verifyPageCache($listing_path, 'HIT', $tags);


    // Verify that after modifying the referenced entity, there is a cache miss
    // for both the referencing entity, and the listing of referencing entities,
    // but not for the non-referencing entity.
    $this->pass("Test modification of referenced entity.", 'Debug');
    $this->entity->save();
    $this->verifyPageCache($referencing_entity_path, 'MISS');
    $this->verifyPageCache($listing_path, 'MISS');
    $this->verifyPageCache($non_referencing_entity_path, 'HIT');

    // Verify cache hits.
    $this->verifyPageCache($referencing_entity_path, 'HIT');
    $this->verifyPageCache($listing_path, 'HIT');


    // Verify that after modifying the referencing entity, there is a cache miss
    // for both the referencing entity, and the listing of referencing entities,
    // but not for the non-referencing entity.
    $this->pass("Test modification of referencing entity.", 'Debug');
    $this->referencing_entity->save();
    $this->verifyPageCache($referencing_entity_path, 'MISS');
    $this->verifyPageCache($listing_path, 'MISS');
    $this->verifyPageCache($non_referencing_entity_path, 'HIT');

    // Verify cache hits.
    $this->verifyPageCache($referencing_entity_path, 'HIT');
    $this->verifyPageCache($listing_path, 'HIT');


    // Verify that after modifying the non-referencing entity, there is a cache
    // miss for only the non-referencing entity, not for the referencing entity,
    // nor for the listing of referencing entities.
    $this->pass("Test modification of non-referencing entity.", 'Debug');
    $this->non_referencing_entity->save();
    $this->verifyPageCache($referencing_entity_path, 'HIT');
    $this->verifyPageCache($listing_path, 'HIT');
    $this->verifyPageCache($non_referencing_entity_path, 'MISS');

    // Verify cache hits.
    $this->verifyPageCache($non_referencing_entity_path, 'HIT');


365
    if ($this->entity->getEntityType()->hasControllerClass('view_builder')) {
366 367
      // Verify that after modifying the entity's display, there is a cache miss
      // for both the referencing entity, and the listing of referencing
368
      // entities, but not for the non-referencing entity.
369 370 371
      $referenced_entity_view_mode = $this->selectViewMode($this->entity->getEntityTypeId());
      $this->pass("Test modification of referenced entity's '$referenced_entity_view_mode' display.", 'Debug');
      $entity_display = entity_get_display($entity_type, $this->entity->bundle(), $referenced_entity_view_mode);
372 373 374 375
      $entity_display->save();
      $this->verifyPageCache($referencing_entity_path, 'MISS');
      $this->verifyPageCache($listing_path, 'MISS');
      $this->verifyPageCache($non_referencing_entity_path, 'HIT');
376

377 378 379 380
      // Verify cache hits.
      $this->verifyPageCache($referencing_entity_path, 'HIT');
      $this->verifyPageCache($listing_path, 'HIT');
    }
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436


    $bundle_entity_type = $this->entity->getEntityType()->getBundleEntityType();
    if ($bundle_entity_type !== 'bundle') {
      // Verify that after modifying the corresponding bundle entity, there is a
      // cache miss for both the referencing entity, and the listing of
      // referencing entities, but not for the non-referencing entity.
      $this->pass("Test modification of referenced entity's bundle entity.", 'Debug');
      $bundle_entity = entity_load($bundle_entity_type, $this->entity->bundle());
      $bundle_entity->save();
      $this->verifyPageCache($referencing_entity_path, 'MISS');
      $this->verifyPageCache($listing_path, 'MISS');
      $this->verifyPageCache($non_referencing_entity_path, 'HIT');

      // Verify cache hits.
      $this->verifyPageCache($referencing_entity_path, 'HIT');
      $this->verifyPageCache($listing_path, 'HIT');
    }


    if ($this->entity->getEntityType()->isFieldable()) {
      // Verify that after modifying a configurable field on the entity, there
      // is a cache miss.
      $this->pass("Test modification of referenced entity's configurable field.", 'Debug');
      $field_name = $this->entity->getEntityTypeId() . '.configurable_field';
      $field = entity_load('field_config', $field_name);
      $field->save();
      $this->verifyPageCache($referencing_entity_path, 'MISS');
      $this->verifyPageCache($listing_path, 'MISS');
      $this->verifyPageCache($non_referencing_entity_path, 'HIT');

      // Verify cache hits.
      $this->verifyPageCache($referencing_entity_path, 'HIT');
      $this->verifyPageCache($listing_path, 'HIT');


      // Verify that after modifying a configurable field instance on the
      // entity, there is a cache miss.
      $this->pass("Test modification of referenced entity's configurable field instance.", 'Debug');
      $field_instance_name = $this->entity->getEntityTypeId() . '.' . $this->entity->bundle() . '.configurable_field';
      $field_instance = entity_load('field_instance_config', $field_instance_name);
      $field_instance->save();
      $this->verifyPageCache($referencing_entity_path, 'MISS');
      $this->verifyPageCache($listing_path, 'MISS');
      $this->verifyPageCache($non_referencing_entity_path, 'HIT');

      // Verify cache hits.
      $this->verifyPageCache($referencing_entity_path, 'HIT');
      $this->verifyPageCache($listing_path, 'HIT');
    }


    // Verify that after invalidating the entity's cache tag directly,  there is
    // a cache miss for both the referencing entity, and the listing of
    // referencing entities, but not for the non-referencing entity.
    $this->pass("Test invalidation of referenced entity's cache tag.", 'Debug');
437
    Cache::invalidateTags($this->entity->getCacheTag());
438 439 440 441 442 443 444 445 446
    $this->verifyPageCache($referencing_entity_path, 'MISS');
    $this->verifyPageCache($listing_path, 'MISS');
    $this->verifyPageCache($non_referencing_entity_path, 'HIT');

    // Verify cache hits.
    $this->verifyPageCache($referencing_entity_path, 'HIT');
    $this->verifyPageCache($listing_path, 'HIT');


447 448 449 450 451 452 453 454 455
    if (!empty($view_cache_tag)) {
      // Verify that after invalidating the generic entity type's view cache tag
      // directly, there is a cache miss for both the referencing entity, and the
      // listing of referencing entities, but not for the non-referencing entity.
      $this->pass("Test invalidation of referenced entity's 'view' cache tag.", 'Debug');
      Cache::invalidateTags($view_cache_tag);
      $this->verifyPageCache($referencing_entity_path, 'MISS');
      $this->verifyPageCache($listing_path, 'MISS');
      $this->verifyPageCache($non_referencing_entity_path, 'HIT');
456

457 458 459 460
      // Verify cache hits.
      $this->verifyPageCache($referencing_entity_path, 'HIT');
      $this->verifyPageCache($listing_path, 'HIT');
    }
461 462 463 464 465 466 467 468 469 470 471

    // Verify that after deleting the entity, there is a cache miss for both the
    // referencing entity, and the listing of referencing entities, but not for
    // the non-referencing entity.
    $this->pass('Test deletion of referenced entity.', 'Debug');
    $this->entity->delete();
    $this->verifyPageCache($referencing_entity_path, 'MISS');
    $this->verifyPageCache($listing_path, 'MISS');
    $this->verifyPageCache($non_referencing_entity_path, 'HIT');

    // Verify cache hits.
472 473 474 475 476
    $referencing_entity_cache_tags = NestedArray::mergeDeep(
      $this->referencing_entity->getCacheTag(),
      \Drupal::entityManager()->getViewBuilder('entity_test')->getCacheTag()
    );
    $referencing_entity_cache_tags = explode(' ', HtmlViewSubscriber::convertCacheTagsToHeader($referencing_entity_cache_tags));
477
    $tags = array_merge($render_cache_tags, $theme_cache_tags, $referencing_entity_cache_tags);
478
    $this->verifyPageCache($referencing_entity_path, 'HIT', $tags);
479 480
    $tags = array_merge($render_cache_tags, $theme_cache_tags);
    $this->verifyPageCache($listing_path, 'HIT', $tags);
481 482
  }

483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
  /**
   * Verify that a given render cache entry exists, with the correct cache tags.
   *
   * @param string $cid
   *   The render cache item ID.
   * @param array $tags
   *   An array of expected cache tags.
   */
  protected function verifyRenderCache($cid, array $tags) {
    // Also verify the existence of an entity render cache entry.
    $cache_entry = \Drupal::cache('render')->get($cid);
    $this->assertTrue($cache_entry, 'A render cache entry exists.');
    sort($cache_entry->tags);
    sort($tags);
    $this->assertIdentical($cache_entry->tags, $tags);
  }

500
}