EntityHasFieldConstraintValidatorTest.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace Drupal\KernelTests\Core\Entity;
  3. use Drupal\field\Entity\FieldConfig;
  4. use Drupal\field\Entity\FieldStorageConfig;
  5. /**
  6. * @covers \Drupal\Core\Entity\Plugin\Validation\Constraint\EntityHasFieldConstraintValidator
  7. *
  8. * @group Entity
  9. */
  10. class EntityHasFieldConstraintValidatorTest extends EntityKernelTestBase {
  11. /**
  12. * {@inheritdoc}
  13. */
  14. public static $modules = ['entity_test_constraints'];
  15. /**
  16. * {@inheritdoc}
  17. */
  18. protected function setUp() {
  19. parent::setUp();
  20. $this->installEntitySchema('entity_test_constraints');
  21. $this->createUser();
  22. }
  23. public function testValidation() {
  24. $this->state->set('entity_test_constraints.build', [
  25. 'EntityHasField' => 'body',
  26. ]);
  27. /** @var \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager */
  28. $entity_type_manager = $this->container->get('entity_type.manager');
  29. $entity_type_manager->clearCachedDefinitions();
  30. // Clear the typed data cache so that the entity has the correct constraints
  31. // during validation.
  32. $this->container->get('typed_data_manager')->clearCachedDefinitions();
  33. $storage = $entity_type_manager->getStorage('entity_test_constraints');
  34. /** @var \Drupal\entity_test\Entity\EntityTestConstraints $entity */
  35. $entity = $storage->create();
  36. // We should get a violation if we try to validate the entity before the
  37. // field has been created.
  38. $violations = $entity->validate();
  39. $this->assertCount(1, $violations);
  40. $this->assertEquals($violations[0]->getMessage(), 'The entity must have the <em class="placeholder">body</em> field.');
  41. $storage->save($entity);
  42. // Create the field.
  43. $field_storage = FieldStorageConfig::create([
  44. 'type' => 'string',
  45. 'entity_type' => $entity->getEntityTypeId(),
  46. 'field_name' => 'body',
  47. ]);
  48. $field_storage->save();
  49. FieldConfig::create([
  50. 'field_storage' => $field_storage,
  51. 'bundle' => $entity->bundle(),
  52. ])->save();
  53. // Now that the field has been created, there should be no violations.
  54. $this->assertCount(0, $storage->loadUnchanged(1)->validate());
  55. }
  56. }