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