public function EntityFieldTest::testEntityConstraintValidation

Tests validation constraints provided by the Entity API.

File

drupal/core/modules/system/lib/Drupal/system/Tests/Entity/EntityFieldTest.php, line 532
Definition of Drupal\system\Tests\Entity\EntityFieldTest.

Class

EntityFieldTest
Tests Entity API base functionality.

Namespace

Drupal\system\Tests\Entity

Code

public function testEntityConstraintValidation() {
  $entity = $this
    ->createTestEntity('entity_test');
  $entity
    ->save();
  $entity_definition = array(
    'type' => 'entity',
    'constraints' => array(
      'EntityType' => 'entity_test',
    ),
    'label' => 'Test entity',
  );
  $wrapped_entity = $this->container
    ->get('typed_data')
    ->create($entity_definition, $entity);

  // Test validation the typed data object.
  $violations = $wrapped_entity
    ->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(),
  ));

  // @todo: EntityWrapper can only handle entities with an id.
  $node
    ->save();
  $wrapped_entity
    ->setValue($node);
  $violations = $wrapped_entity
    ->validate();
  $this
    ->assertEqual($violations
    ->count(), 1);

  // Test bundle validation.
  $entity_definition = array(
    'type' => 'entity',
    'constraints' => array(
      'EntityType' => 'node',
      'Bundle' => 'article',
    ),
    'label' => 'Test node',
  );
  $wrapped_entity = $this->container
    ->get('typed_data')
    ->create($entity_definition, $node);
  $violations = $wrapped_entity
    ->validate();
  $this
    ->assertEqual($violations
    ->count(), 1);
  $node->type = 'article';
  $node
    ->save();
  $wrapped_entity
    ->setValue($node);
  $violations = $wrapped_entity
    ->validate();
  $this
    ->assertEqual($violations
    ->count(), 0);
}