You are here

public function EntityReferenceFieldTest::testTargetEntityNoLoad in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/system/src/Tests/Entity/EntityReferenceFieldTest.php \Drupal\system\Tests\Entity\EntityReferenceFieldTest::testTargetEntityNoLoad()

Tests that the target entity is not unnecessarily loaded.

File

core/modules/system/src/Tests/Entity/EntityReferenceFieldTest.php, line 361
Contains \Drupal\system\Tests\Entity\EntityReferenceFieldTest.

Class

EntityReferenceFieldTest
Tests for the entity reference field.

Namespace

Drupal\system\Tests\Entity

Code

public function testTargetEntityNoLoad() {

  // Setup a test entity type with an entity reference field to itself. We use
  // a special storage class throwing exceptions when a load operation is
  // triggered to be able to detect them.
  $entity_type = clone $this->entityManager
    ->getDefinition('entity_test_update');
  $entity_type
    ->setHandlerClass('storage', '\\Drupal\\entity_test\\EntityTestNoLoadStorage');
  $this->state
    ->set('entity_test_update.entity_type', $entity_type);
  $definitions = array(
    'target_reference' => BaseFieldDefinition::create('entity_reference')
      ->setSetting('target_type', $entity_type
      ->id())
      ->setSetting('handler', 'default'),
  );
  $this->state
    ->set('entity_test_update.additional_base_field_definitions', $definitions);
  $this->entityManager
    ->clearCachedDefinitions();
  $this
    ->installEntitySchema($entity_type
    ->id());

  // Create the target entity.
  $storage = $this->entityManager
    ->getStorage($entity_type
    ->id());
  $target_id = $this
    ->generateRandomEntityId();
  $target = $storage
    ->create(array(
    'id' => $target_id,
    'name' => $this
      ->randomString(),
  ));
  $target
    ->save();
  $this
    ->assertEqual($target_id, $target
    ->id(), 'The target entity has a random identifier.');

  // Check that populating the reference with an existing target id does not
  // trigger a load operation.
  $message = 'The target entity was not loaded.';
  try {
    $entity = $this->entityManager
      ->getStorage($entity_type
      ->id())
      ->create(array(
      'name' => $this
        ->randomString(),
    ));
    $entity->target_reference = $target_id;
    $this
      ->pass($message);
  } catch (EntityStorageException $e) {
    $this
      ->fail($message);
  }

  // Check that the storage actually triggers the expected exception when
  // trying to load the target entity.
  $message = 'An exception is thrown when trying to load the target entity';
  try {
    $storage
      ->load($target_id);
    $this
      ->fail($message);
  } catch (EntityStorageException $e) {
    $this
      ->pass($message);
  }
}