Upgraded drupal core with security updates
[yaffs-website] / web / core / modules / field / tests / src / Kernel / FieldCrudTest.php
1 <?php
2
3 namespace Drupal\Tests\field\Kernel;
4
5 use Drupal\Component\Utility\Unicode;
6 use Drupal\Core\Entity\EntityStorageException;
7 use Drupal\Core\Field\FieldException;
8 use Drupal\entity_test\Entity\EntityTest;
9 use Drupal\field\Entity\FieldStorageConfig;
10 use Drupal\field\Entity\FieldConfig;
11
12 /**
13  * Create field entities by attaching fields to entities.
14  *
15  * @coversDefaultClass \Drupal\Core\Field\FieldConfigBase
16  *
17  * @group field
18  */
19 class FieldCrudTest extends FieldKernelTestBase {
20
21   /**
22    * The field storage entity.
23    *
24    * @var \Drupal\field\Entity\FieldStorageConfig
25    */
26   protected $fieldStorage;
27
28   /**
29    * The field entity definition.
30    *
31    * @var array
32    */
33   protected $fieldStorageDefinition;
34
35   /**
36    * The field entity definition.
37    *
38    * @var array
39    */
40   protected $fieldDefinition;
41
42   public function setUp() {
43     parent::setUp();
44
45     $this->fieldStorageDefinition = [
46       'field_name' => Unicode::strtolower($this->randomMachineName()),
47       'entity_type' => 'entity_test',
48       'type' => 'test_field',
49     ];
50     $this->fieldStorage = FieldStorageConfig::create($this->fieldStorageDefinition);
51     $this->fieldStorage->save();
52     $this->fieldDefinition = [
53       'field_name' => $this->fieldStorage->getName(),
54       'entity_type' => 'entity_test',
55       'bundle' => 'entity_test',
56     ];
57   }
58
59   // TODO : test creation with
60   // - a full fledged $field structure, check that all the values are there
61   // - a minimal $field structure, check all default values are set
62   // defer actual $field comparison to a helper function, used for the two cases above,
63   // and for testUpdateField
64
65   /**
66    * Test the creation of a field.
67    */
68   public function testCreateField() {
69     $field = FieldConfig::create($this->fieldDefinition);
70     $field->save();
71
72     $field = FieldConfig::load($field->id());
73     $this->assertTrue($field->getSetting('field_setting_from_config_data'));
74     $this->assertNull($field->getSetting('config_data_from_field_setting'));
75
76     // Read the configuration. Check against raw configuration data rather than
77     // the loaded ConfigEntity, to be sure we check that the defaults are
78     // applied on write.
79     $config = $this->config('field.field.' . $field->id())->get();
80     $field_type_manager = \Drupal::service('plugin.manager.field.field_type');
81
82     $this->assertTrue($config['settings']['config_data_from_field_setting']);
83     $this->assertTrue(!isset($config['settings']['field_setting_from_config_data']));
84
85     // Since we are working with raw configuration, this needs to be unset
86     // manually.
87     // @see Drupal\field_test\Plugin\Field\FieldType\TestItem::fieldSettingsFromConfigData()
88     unset($config['settings']['config_data_from_field_setting']);
89
90     // Check that default values are set.
91     $this->assertEqual($config['required'], FALSE, 'Required defaults to false.');
92     $this->assertIdentical($config['label'], $this->fieldDefinition['field_name'], 'Label defaults to field name.');
93     $this->assertIdentical($config['description'], '', 'Description defaults to empty string.');
94
95     // Check that default settings are set.
96     $this->assertEqual($config['settings'], $field_type_manager->getDefaultFieldSettings($this->fieldStorageDefinition['type']), 'Default field settings have been written.');
97
98     // Check that the denormalized 'field_type' was properly written.
99     $this->assertEqual($config['field_type'], $this->fieldStorageDefinition['type']);
100
101     // Guarantee that the field/bundle combination is unique.
102     try {
103       FieldConfig::create($this->fieldDefinition)->save();
104       $this->fail(t('Cannot create two fields with the same field / bundle combination.'));
105     }
106     catch (EntityStorageException $e) {
107       $this->pass(t('Cannot create two fields with the same field / bundle combination.'));
108     }
109
110     // Check that the specified field exists.
111     try {
112       $this->fieldDefinition['field_name'] = $this->randomMachineName();
113       FieldConfig::create($this->fieldDefinition)->save();
114       $this->fail(t('Cannot create a field with a non-existing storage.'));
115     }
116     catch (FieldException $e) {
117       $this->pass(t('Cannot create a field with a non-existing storage.'));
118     }
119
120     // TODO: test other failures.
121   }
122
123   /**
124    * Tests setting and adding property constraints to a configurable field.
125    *
126    * @covers ::setPropertyConstraints
127    * @covers ::addPropertyConstraints
128    */
129   public function testFieldPropertyConstraints() {
130     $field = FieldConfig::create($this->fieldDefinition);
131     $field->save();
132     $field_name = $this->fieldStorage->getName();
133
134     // Test that constraints are applied to configurable fields. A TestField and
135     // a Range constraint are added dynamically to limit the field to values
136     // between 0 and 32.
137     // @see field_test_entity_bundle_field_info_alter()
138     \Drupal::state()->set('field_test_constraint', $field_name);
139
140     // Clear the field definitions cache so the new constraints added by
141     // field_test_entity_bundle_field_info_alter() are taken into consideration.
142     \Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();
143
144     // Test the newly added property constraints in the same request as when the
145     // caches were cleared. This will test the field definitions that are stored
146     // in the static cache of
147     // \Drupal\Core\Entity\EntityFieldManager::getFieldDefinitions().
148     $this->doFieldPropertyConstraintsTests();
149
150     // In order to test a real-world scenario where the property constraints are
151     // only stored in the persistent cache of
152     // \Drupal\Core\Entity\EntityFieldManager::getFieldDefinitions(), we need to
153     // simulate a new request by removing the 'entity_field.manager' service,
154     // thus forcing it to be re-initialized without static caches.
155     \Drupal::getContainer()->set('entity_field.manager', NULL);
156
157     // This will test the field definitions that are stored in the persistent
158     // cache by \Drupal\Core\Entity\EntityFieldManager::getFieldDefinitions().
159     $this->doFieldPropertyConstraintsTests();
160   }
161
162   /**
163    * Tests configurable field validation.
164    *
165    * @see field_test_entity_bundle_field_info_alter()
166    */
167   protected function doFieldPropertyConstraintsTests() {
168     $field_name = $this->fieldStorage->getName();
169
170     // Check that a valid value (not -2 and between 0 and 32) doesn't trigger
171     // any violation.
172     $entity = EntityTest::create();
173     $entity->set($field_name, 1);
174     $violations = $entity->validate();
175     $this->assertCount(0, $violations, 'No violations found when in-range value passed.');
176
177     // Check that a value that is specifically restricted triggers both
178     // violations.
179     $entity->set($field_name, -2);
180     $violations = $entity->validate();
181     $this->assertCount(2, $violations, 'Two violations found when using a null and outside the range value.');
182
183     $this->assertEquals($field_name . '.0.value', $violations[0]->getPropertyPath());
184     $this->assertEquals(t('%name does not accept the value @value.', ['%name' => $field_name, '@value' => -2]), $violations[0]->getMessage());
185
186     $this->assertEquals($field_name . '.0.value', $violations[1]->getPropertyPath());
187     $this->assertEquals(t('This value should be %limit or more.', ['%limit' => 0]), $violations[1]->getMessage());
188
189     // Check that a value that is not specifically restricted but outside the
190     // range triggers the expected violation.
191     $entity->set($field_name, 33);
192     $violations = $entity->validate();
193     $this->assertCount(1, $violations, 'Violations found when using value outside the range.');
194     $this->assertEquals($field_name . '.0.value', $violations[0]->getPropertyPath());
195     $this->assertEquals(t('This value should be %limit or less.', ['%limit' => 32]), $violations[0]->getMessage());
196   }
197
198   /**
199    * Test creating a field with custom storage set.
200    */
201   public function testCreateFieldCustomStorage() {
202     $field_name = Unicode::strtolower($this->randomMachineName());
203     \Drupal::state()->set('field_test_custom_storage', $field_name);
204
205     $field_storage = FieldStorageConfig::create([
206       'field_name' => $field_name,
207       'entity_type' => 'entity_test',
208       'type' => 'test_field',
209       'custom_storage' => TRUE,
210     ]);
211     $field_storage->save();
212
213     $field = FieldConfig::create([
214       'field_name' => $field_storage->getName(),
215       'entity_type' => 'entity_test',
216       'bundle' => 'entity_test',
217     ]);
218     $field->save();
219
220     \Drupal::entityManager()->clearCachedFieldDefinitions();
221
222     // Check that no table has been created for the field.
223     $this->assertFalse(\Drupal::database()->schema()->tableExists('entity_test__' . $field_storage->getName()));
224
225     // Save an entity with a value in the custom storage field and verify no
226     // data is retrieved on load.
227     $entity = EntityTest::create(['name' => $this->randomString(), $field_name => 'Test value']);
228     $this->assertIdentical('Test value', $entity->{$field_name}->value, 'The test value is set on the field.');
229
230     $entity->save();
231     $entity = EntityTest::load($entity->id());
232
233     $this->assertNull($entity->{$field_name}->value, 'The loaded entity field value is NULL.');
234   }
235
236   /**
237    * Test reading back a field definition.
238    */
239   public function testReadField() {
240     FieldConfig::create($this->fieldDefinition)->save();
241
242     // Read the field back.
243     $field = FieldConfig::load('entity_test.' . $this->fieldDefinition['bundle'] . '.' . $this->fieldDefinition['field_name']);
244     $this->assertTrue($this->fieldDefinition['field_name'] == $field->getName(), 'The field was properly read.');
245     $this->assertTrue($this->fieldDefinition['entity_type'] == $field->getTargetEntityTypeId(), 'The field was properly read.');
246     $this->assertTrue($this->fieldDefinition['bundle'] == $field->getTargetBundle(), 'The field was properly read.');
247   }
248
249   /**
250    * Test the update of a field.
251    */
252   public function testUpdateField() {
253     FieldConfig::create($this->fieldDefinition)->save();
254
255     // Check that basic changes are saved.
256     $field = FieldConfig::load('entity_test.' . $this->fieldDefinition['bundle'] . '.' . $this->fieldDefinition['field_name']);
257     $field->setRequired(!$field->isRequired());
258     $field->setLabel($this->randomMachineName());
259     $field->set('description', $this->randomMachineName());
260     $field->setSetting('test_field_setting', $this->randomMachineName());
261     $field->save();
262
263     $field_new = FieldConfig::load('entity_test.' . $this->fieldDefinition['bundle'] . '.' . $this->fieldDefinition['field_name']);
264     $this->assertEqual($field->isRequired(), $field_new->isRequired(), '"required" change is saved');
265     $this->assertEqual($field->getLabel(), $field_new->getLabel(), '"label" change is saved');
266     $this->assertEqual($field->getDescription(), $field_new->getDescription(), '"description" change is saved');
267
268     // TODO: test failures.
269   }
270
271   /**
272    * Test the deletion of a field.
273    */
274   public function testDeleteField() {
275     // TODO: Test deletion of the data stored in the field also.
276     // Need to check that data for a 'deleted' field / storage doesn't get loaded
277     // Need to check data marked deleted is cleaned on cron (not implemented yet...)
278
279     // Create two fields for the same field storage so we can test that only one
280     // is deleted.
281     FieldConfig::create($this->fieldDefinition)->save();
282     $another_field_definition = $this->fieldDefinition;
283     $another_field_definition['bundle'] .= '_another_bundle';
284     entity_test_create_bundle($another_field_definition['bundle']);
285     FieldConfig::create($another_field_definition)->save();
286
287     // Test that the first field is not deleted, and then delete it.
288     $field = current(entity_load_multiple_by_properties('field_config', ['entity_type' => 'entity_test', 'field_name' => $this->fieldDefinition['field_name'], 'bundle' => $this->fieldDefinition['bundle'], 'include_deleted' => TRUE]));
289     $this->assertTrue(!empty($field) && empty($field->deleted), 'A new field is not marked for deletion.');
290     $field->delete();
291
292     // Make sure the field is marked as deleted when it is specifically loaded.
293     $field = current(entity_load_multiple_by_properties('field_config', ['entity_type' => 'entity_test', 'field_name' => $this->fieldDefinition['field_name'], 'bundle' => $this->fieldDefinition['bundle'], 'include_deleted' => TRUE]));
294     $this->assertTrue($field->isDeleted(), 'A deleted field is marked for deletion.');
295
296     // Try to load the field normally and make sure it does not show up.
297     $field = FieldConfig::load('entity_test.' . '.' . $this->fieldDefinition['bundle'] . '.' . $this->fieldDefinition['field_name']);
298     $this->assertTrue(empty($field), 'A deleted field is not loaded by default.');
299
300     // Make sure the other field is not deleted.
301     $another_field = FieldConfig::load('entity_test.' . $another_field_definition['bundle'] . '.' . $another_field_definition['field_name']);
302     $this->assertTrue(!empty($another_field) && empty($another_field->deleted), 'A non-deleted field is not marked for deletion.');
303   }
304
305   /**
306    * Tests the cross deletion behavior between field storages and fields.
307    */
308   public function testDeleteFieldCrossDeletion() {
309     $field_definition_2 = $this->fieldDefinition;
310     $field_definition_2['bundle'] .= '_another_bundle';
311     entity_test_create_bundle($field_definition_2['bundle']);
312
313     // Check that deletion of a field storage deletes its fields.
314     $field_storage = $this->fieldStorage;
315     FieldConfig::create($this->fieldDefinition)->save();
316     FieldConfig::create($field_definition_2)->save();
317     $field_storage->delete();
318     $this->assertFalse(FieldConfig::loadByName('entity_test', $this->fieldDefinition['bundle'], $field_storage->getName()));
319     $this->assertFalse(FieldConfig::loadByName('entity_test', $field_definition_2['bundle'], $field_storage->getName()));
320
321     // Check that deletion of the last field deletes the storage.
322     $field_storage = FieldStorageConfig::create($this->fieldStorageDefinition);
323     $field_storage->save();
324     $field = FieldConfig::create($this->fieldDefinition);
325     $field->save();
326     $field_2 = FieldConfig::create($field_definition_2);
327     $field_2->save();
328     $field->delete();
329     $this->assertTrue(FieldStorageConfig::loadByName('entity_test', $field_storage->getName()));
330     $field_2->delete();
331     $this->assertFalse(FieldStorageConfig::loadByName('entity_test', $field_storage->getName()));
332
333     // Check that deletion of all fields using a storage simultaneously deletes
334     // the storage.
335     $field_storage = FieldStorageConfig::create($this->fieldStorageDefinition);
336     $field_storage->save();
337     $field = FieldConfig::create($this->fieldDefinition);
338     $field->save();
339     $field_2 = FieldConfig::create($field_definition_2);
340     $field_2->save();
341     $this->container->get('entity.manager')->getStorage('field_config')->delete([$field, $field_2]);
342     $this->assertFalse(FieldStorageConfig::loadByName('entity_test', $field_storage->getName()));
343   }
344
345 }