You are here

public function EntityTypeConstraintsTest::testConstraintDefinition in Zircon Profile 8

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

Tests defining entity constraints via entity type annotations and hooks.

File

core/modules/system/src/Tests/Entity/EntityTypeConstraintsTest.php, line 30
Contains \Drupal\system\Tests\Entity\EntityTypeConstraintsTest.

Class

EntityTypeConstraintsTest
Tests entity level validation constraints.

Namespace

Drupal\system\Tests\Entity

Code

public function testConstraintDefinition() {

  // Test reading the annotation. There should be two constraints, the defined
  // constraint and the automatically added EntityChanged constraint.
  $entity_type = $this->entityManager
    ->getDefinition('entity_test_constraints');
  $default_constraints = [
    'NotNull' => [],
    'EntityChanged' => NULL,
  ];
  $this
    ->assertEqual($default_constraints, $entity_type
    ->getConstraints());

  // Enable our test module and test extending constraints.
  $this
    ->enableModules(array_merge(static::$modules, [
    'entity_test_constraints',
  ]));
  $this->container
    ->get('module_handler')
    ->resetImplementations();
  $extra_constraints = [
    'Test' => [],
  ];
  $this->state
    ->set('entity_test_constraints.build', $extra_constraints);

  // Re-fetch the entity manager from the new container built after the new
  // modules were enabled.
  $this->entityManager = $this->container
    ->get('entity.manager');
  $this->entityManager
    ->clearCachedDefinitions();
  $entity_type = $this->entityManager
    ->getDefinition('entity_test_constraints');
  $this
    ->assertEqual($default_constraints + $extra_constraints, $entity_type
    ->getConstraints());

  // Test altering constraints.
  $altered_constraints = [
    'Test' => [
      'some_setting' => TRUE,
    ],
  ];
  $this->state
    ->set('entity_test_constraints.alter', $altered_constraints);

  // Clear the cache in state instance in the Drupal container, so it can pick
  // up the modified value.
  \Drupal::state()
    ->resetCache();
  $this->entityManager
    ->clearCachedDefinitions();
  $entity_type = $this->entityManager
    ->getDefinition('entity_test_constraints');
  $this
    ->assertEqual($altered_constraints, $entity_type
    ->getConstraints());
}