You are here

public function EntityFieldTest::testEntityConstraintValidation in Zircon Profile 8

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

Tests validation constraints provided by the Entity API.

File

core/modules/system/src/Tests/Entity/EntityFieldTest.php, line 660
Contains \Drupal\system\Tests\Entity\EntityFieldTest.

Class

EntityFieldTest
Tests the Entity Field API.

Namespace

Drupal\system\Tests\Entity

Code

public function testEntityConstraintValidation() {
  $entity = $this
    ->createTestEntity('entity_test');
  $entity
    ->save();

  // Create a reference field item and let it reference the entity.
  $definition = BaseFieldDefinition::create('entity_reference')
    ->setLabel('Test entity')
    ->setSetting('target_type', 'entity_test');
  $reference_field = \Drupal::typedDataManager()
    ->create($definition);
  $reference = $reference_field
    ->appendItem(array(
    'entity' => $entity,
  ))
    ->get('entity');

  // Test validation the typed data object.
  $violations = $reference
    ->validate();
  $this
    ->assertEqual($violations
    ->count(), 0);

  // Test validating an entity of the wrong type.
  $user = $this
    ->createUser();
  $user
    ->save();
  $node = entity_create('node', array(
    'type' => 'page',
    'uid' => $user
      ->id(),
    'title' => $this
      ->randomString(),
  ));
  $reference
    ->setValue($node);
  $violations = $reference
    ->validate();
  $this
    ->assertEqual($violations
    ->count(), 1);

  // Test bundle validation.
  NodeType::create(array(
    'type' => 'article',
  ))
    ->save();
  $definition = BaseFieldDefinition::create('entity_reference')
    ->setLabel('Test entity')
    ->setSetting('target_type', 'node')
    ->setSetting('handler_settings', [
    'target_bundles' => [
      'article' => 'article',
    ],
  ]);
  $reference_field = \Drupal::TypedDataManager()
    ->create($definition);
  $reference_field
    ->appendItem(array(
    'entity' => $node,
  ));
  $violations = $reference_field
    ->validate();
  $this
    ->assertEqual($violations
    ->count(), 1);
  $node = entity_create('node', array(
    'type' => 'article',
    'uid' => $user
      ->id(),
    'title' => $this
      ->randomString(),
  ));
  $node
    ->save();
  $reference_field->entity = $node;
  $violations = $reference_field
    ->validate();
  $this
    ->assertEqual($violations
    ->count(), 0);
}