bf2a147e0a1456245fd45e57ac026e9d19b60711
[yaffs-website] / web / core / tests / Drupal / KernelTests / Core / Entity / EntityValidationTest.php
1 <?php
2
3 namespace Drupal\KernelTests\Core\Entity;
4
5 use Drupal\Core\Entity\Plugin\Validation\Constraint\CompositeConstraintBase;
6
7 /**
8  * Tests the Entity Validation API.
9  *
10  * @group Entity
11  */
12 class EntityValidationTest extends EntityKernelTestBase {
13
14   /**
15    * Modules to enable.
16    *
17    * @var array
18    */
19   public static $modules = ['filter', 'text'];
20
21   /**
22    * @var string
23    */
24   protected $entityName;
25
26   /**
27    * @var \Drupal\user\Entity\User
28    */
29   protected $entityUser;
30
31   /**
32    * @var string
33    */
34   protected $entityFieldText;
35
36   /**
37    * {@inheritdoc}
38    */
39   protected function setUp() {
40     parent::setUp();
41
42     // Create the test field.
43     module_load_install('entity_test');
44     entity_test_install();
45
46     // Install required default configuration for filter module.
47     $this->installConfig(['system', 'filter']);
48   }
49
50   /**
51    * Creates a test entity.
52    *
53    * @param string $entity_type
54    *   An entity type.
55    *
56    * @return \Drupal\Core\Entity\EntityInterface
57    *   The created test entity.
58    */
59   protected function createTestEntity($entity_type) {
60     $this->entityName = $this->randomMachineName();
61     $this->entityUser = $this->createUser();
62
63     // Pass in the value of the name field when creating. With the user
64     // field we test setting a field after creation.
65     $entity = $this->container->get('entity_type.manager')
66       ->getStorage($entity_type)
67       ->create();
68     $entity->user_id->target_id = $this->entityUser->id();
69     $entity->name->value = $this->entityName;
70
71     // Set a value for the test field.
72     if ($entity->hasField('field_test_text')) {
73       $this->entityFieldText = $this->randomMachineName();
74       $entity->field_test_text->value = $this->entityFieldText;
75     }
76
77     return $entity;
78   }
79
80   /**
81    * Tests validating test entity types.
82    */
83   public function testValidation() {
84     // Ensure that the constraint manager is marked as cached cleared.
85
86     // Use the protected property on the cache_clearer first to check whether
87     // the constraint manager is added there.
88
89     // Ensure that the proxy class is initialized, which has the necessary
90     // method calls attached.
91     \Drupal::service('plugin.cache_clearer');
92     $plugin_cache_clearer = \Drupal::service('drupal.proxy_original_service.plugin.cache_clearer');
93     $get_cached_discoveries = function () {
94       return $this->cachedDiscoveries;
95     };
96     $get_cached_discoveries = $get_cached_discoveries->bindTo($plugin_cache_clearer, $plugin_cache_clearer);
97     $cached_discoveries = $get_cached_discoveries();
98     $cached_discovery_classes = [];
99     foreach ($cached_discoveries as $cached_discovery) {
100       $cached_discovery_classes[] = get_class($cached_discovery);
101     }
102     $this->assertTrue(in_array('Drupal\Core\Validation\ConstraintManager', $cached_discovery_classes));
103
104     // All entity variations have to have the same results.
105     foreach (entity_test_entity_types() as $entity_type) {
106       $this->checkValidation($entity_type);
107     }
108   }
109
110   /**
111    * Executes the validation test set for a defined entity type.
112    *
113    * @param string $entity_type
114    *   The entity type to run the tests with.
115    */
116   protected function checkValidation($entity_type) {
117     $entity = $this->createTestEntity($entity_type);
118     $violations = $entity->validate();
119     $this->assertEqual($violations->count(), 0, 'Validation passes.');
120
121     // Test triggering a fail for each of the constraints specified.
122     $test_entity = clone $entity;
123     $test_entity->id->value = -1;
124     $violations = $test_entity->validate();
125     $this->assertEqual($violations->count(), 1, 'Validation failed.');
126     $this->assertEqual($violations[0]->getMessage(), t('%name: The integer must be larger or equal to %min.', ['%name' => 'ID', '%min' => 0]));
127
128     $test_entity = clone $entity;
129     $test_entity->uuid->value = $this->randomString(129);
130     $violations = $test_entity->validate();
131     $this->assertEqual($violations->count(), 1, 'Validation failed.');
132     $this->assertEqual($violations[0]->getMessage(), t('%name: may not be longer than @max characters.', ['%name' => 'UUID', '@max' => 128]));
133
134     $test_entity = clone $entity;
135     $langcode_key = $this->entityManager->getDefinition($entity_type)->getKey('langcode');
136     $test_entity->{$langcode_key}->value = $this->randomString(13);
137     $violations = $test_entity->validate();
138     // This should fail on AllowedValues and Length constraints.
139     $this->assertEqual($violations->count(), 2, 'Validation failed.');
140     $this->assertEqual($violations[0]->getMessage(), t('This value is too long. It should have %limit characters or less.', ['%limit' => '12']));
141     $this->assertEqual($violations[1]->getMessage(), t('The value you selected is not a valid choice.'));
142
143     $test_entity = clone $entity;
144     $test_entity->type->value = NULL;
145     $violations = $test_entity->validate();
146     $this->assertEqual($violations->count(), 1, 'Validation failed.');
147     $this->assertEqual($violations[0]->getMessage(), t('This value should not be null.'));
148
149     $test_entity = clone $entity;
150     $test_entity->name->value = $this->randomString(33);
151     $violations = $test_entity->validate();
152     $this->assertEqual($violations->count(), 1, 'Validation failed.');
153     $this->assertEqual($violations[0]->getMessage(), t('%name: may not be longer than @max characters.', ['%name' => 'Name', '@max' => 32]));
154
155     // Make sure the information provided by a violation is correct.
156     $violation = $violations[0];
157     $this->assertEqual($violation->getRoot()->getValue(), $test_entity, 'Violation root is entity.');
158     $this->assertEqual($violation->getPropertyPath(), 'name.0.value', 'Violation property path is correct.');
159     $this->assertEqual($violation->getInvalidValue(), $test_entity->name->value, 'Violation contains invalid value.');
160
161     $test_entity = clone $entity;
162     $test_entity->set('user_id', 9999);
163     $violations = $test_entity->validate();
164     $this->assertEqual($violations->count(), 1, 'Validation failed.');
165     $this->assertEqual($violations[0]->getMessage(), t('The referenced entity (%type: %id) does not exist.', ['%type' => 'user', '%id' => 9999]));
166
167     $test_entity = clone $entity;
168     $test_entity->field_test_text->format = $this->randomString(33);
169     $violations = $test_entity->validate();
170     $this->assertEqual($violations->count(), 1, 'Validation failed.');
171     $this->assertEqual($violations[0]->getMessage(), t('The value you selected is not a valid choice.'));
172
173     // Make sure the information provided by a violation is correct.
174     $violation = $violations[0];
175     $this->assertEqual($violation->getRoot()->getValue(), $test_entity, 'Violation root is entity.');
176     $this->assertEqual($violation->getPropertyPath(), 'field_test_text.0.format', 'Violation property path is correct.');
177     $this->assertEqual($violation->getInvalidValue(), $test_entity->field_test_text->format, 'Violation contains invalid value.');
178   }
179
180   /**
181    * Tests composite constraints.
182    */
183   public function testCompositeConstraintValidation() {
184     $entity = $this->createTestEntity('entity_test_composite_constraint');
185     $violations = $entity->validate();
186     $this->assertEqual($violations->count(), 0);
187
188     // Trigger violation condition.
189     $entity->name->value = 'test';
190     $entity->type->value = 'test2';
191     $violations = $entity->validate();
192     $this->assertEqual($violations->count(), 1);
193
194     // Make sure we can determine this is composite constraint.
195     $constraint = $violations[0]->getConstraint();
196     $this->assertTrue($constraint instanceof CompositeConstraintBase, 'Constraint is composite constraint.');
197     $this->assertEqual('type', $violations[0]->getPropertyPath());
198
199     /** @var CompositeConstraintBase $constraint */
200     $this->assertEqual($constraint->coversFields(), ['name', 'type'], 'Information about covered fields can be retrieved.');
201   }
202
203 }