You are here

public function EntityFieldTest::testEntityConstraintValidation in Drupal 9

Same name and namespace in other branches
  1. 8 core/tests/Drupal/KernelTests/Core/Entity/EntityFieldTest.php \Drupal\KernelTests\Core\Entity\EntityFieldTest::testEntityConstraintValidation()

Tests validation constraints provided by the Entity API.

File

core/tests/Drupal/KernelTests/Core/Entity/EntityFieldTest.php, line 686

Class

EntityFieldTest
Tests the Entity Field API.

Namespace

Drupal\KernelTests\Core\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([
    'entity' => $entity,
  ])
    ->get('entity');

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

  // Test validating an entity of the wrong type.
  $user = $this
    ->createUser();
  $user
    ->save();
  $node = $node = Node::create([
    'type' => 'page',
    'uid' => $user
      ->id(),
    'title' => $this
      ->randomString(),
  ]);
  $reference
    ->setValue($node);
  $violations = $reference
    ->validate();
  $this
    ->assertEquals(1, $violations
    ->count());

  // Test bundle validation.
  NodeType::create([
    '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([
    'entity' => $node,
  ]);
  $violations = $reference_field
    ->validate();
  $this
    ->assertEquals(1, $violations
    ->count());
  $node = Node::create([
    'type' => 'article',
    'uid' => $user
      ->id(),
    'title' => $this
      ->randomString(),
  ]);
  $node
    ->save();
  $reference_field->entity = $node;
  $violations = $reference_field
    ->validate();
  $this
    ->assertEquals(0, $violations
    ->count());
}