function ContentEntityCacheTest::testNonDefaultRevision

Test swapping revisions in hook_entity_preload().

File

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

Class

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

Namespace

Drupal\KernelTests\Core\Entity

Code

public function testNonDefaultRevision() : void {
  \Drupal::state()->set('enable_hook', TRUE);
  /** @var \Drupal\Core\Entity\RevisionableStorageInterface $storage */
  $storage = $this->container
    ->get('entity_type.manager')
    ->getStorage($this->revEntityTypeId);
  $revision_ids = [];
  // Create a revisionable entity and save it. We now have entity with ID 1
  // and single revision with revision ID 1, which is default one.
  $entity = EntityTestMulRev::create([
    'name' => 'Old name',
  ]);
  $entity->save();
  $default_revision_id = $entity->getRevisionId();
  $revision_ids[] = $default_revision_id;
  // Load the created entity and create a new revision.
  $loaded = EntityTestMulRev::load($entity->id());
  $loaded->setName('New name');
  // Following two lines simulate what workspaces do on saving entities in
  // entityPresave for non-default workspaces. All revisions there are set to
  // non-default. See comments to
  // Drupal\workspaces\EntityOperations::entityPresave().
  // This creates a revision with revision ID 2 for entity with ID 1.
  $loaded->setNewRevision(TRUE);
  $loaded->isDefaultRevision(FALSE);
  $loaded->save();
  $expected_revision_id = $loaded->getRevisionId();
  $revision_ids[] = $expected_revision_id;
  // After loading revisions, default revision will be in static cache for
  // entity. But on entity load, it is swapped in hook_entity_preload().
  $storage->loadMultipleRevisions($revision_ids);
  \Drupal::keyValue('entity_test_preload_entities')->set($this->revEntityTypeId, [
    $entity->id() => $loaded->getRevisionId(),
  ]);
  $loaded = EntityTestMulRev::load($entity->id());
  $revision = $storage->loadRevision($loaded->getRevisionId());
  $this->assertEquals($loaded->getRevisionId(), $expected_revision_id);
  $this->assertEquals($revision->getRevisionId(), $expected_revision_id);
  // Since the preloaded entity is written back into the default and revision
  // static cache, the two objects are the same.
  $this->assertSame($revision, $loaded);
}

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