function ContentEntityCacheTest::testCacheNonRevField

Tests loading a cached revision after a non-rev field has been changed.

File

core/tests/Drupal/KernelTests/Core/Entity/ContentEntityCacheTest.php, line 199

Class

ContentEntityCacheTest
Tests the entity static cache when used by content entities.

Namespace

Drupal\KernelTests\Core\Entity

Code

public function testCacheNonRevField() : void {
  /** @var \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager */
  $entity_type_manager = $this->container
    ->get('entity_type.manager');
  /** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
  $storage = $entity_type_manager->getStorage($this->revEntityTypeId);
  $rev_entity_type = $entity_type_manager->getDefinition($this->revEntityTypeId);
  $this->assertTrue($rev_entity_type->isStaticallyCacheable());
  $this->assertTrue($rev_entity_type->isPersistentlyCacheable());
  $this->assertTrue($rev_entity_type->isRevisionable());
  /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
  $entity = $storage->create();
  $entity->set('non_rev_field', 'a');
  $entity->save();
  $non_default_first_rev_id = $entity->getRevisionId();
  $entity->set('non_rev_field', 'b');
  $entity->setNewRevision();
  $entity->save();
  $non_default_second_rev_id = $entity->getRevisionId();
  // Load the entity by the revision ID so that it gets cached into the
  // persistent cache.
  $storage->loadRevision($non_default_second_rev_id);
  // Create a new revision based on the first one, which will leave the second
  // revision in the persistent cache - i.e. when saving a revision only the
  // revision it originates from will be deleted from the persistent cache.
  $entity = $storage->loadRevision($non_default_first_rev_id);
  $entity->set('non_rev_field', 'c');
  $entity->setNewRevision();
  // Fields in the base table are updated only when saving a default revision.
  // As we've picked up an old revision we have to explicitly declare it as
  // default before saving it.
  $entity->isDefaultRevision(TRUE);
  $entity->save();
  $default_rev_id = $entity->getRevisionId();
  // Ensure that the middle non-default revision will contain the latest
  // value of the non-revisionable field.
  $entity = $storage->loadRevision($non_default_second_rev_id);
  $this->assertEquals('c', $entity->get('non_rev_field')->value);
  // Ensure that any other revisions contain the latest value of the
  // non-revisionable field.
  $entity = $storage->loadRevision($non_default_first_rev_id);
  $this->assertEquals('c', $entity->get('non_rev_field')->value);
  $entity = $storage->loadRevision($default_rev_id);
  $this->assertEquals('c', $entity->get('non_rev_field')->value);
  $entity = $storage->load($entity->id());
  $this->assertEquals('c', $entity->get('non_rev_field')->value);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.