Further Drupal 8.6.4 changes. Some core files were not committed before a commit...
[yaffs-website] / web / core / modules / media / tests / src / Kernel / MediaSourceTest.php
1 <?php
2
3 namespace Drupal\Tests\media\Kernel;
4
5 use Drupal\Core\Form\FormState;
6 use Drupal\field\Entity\FieldConfig;
7 use Drupal\field\Entity\FieldStorageConfig;
8 use Drupal\media\Entity\Media;
9 use Drupal\media\Entity\MediaType;
10
11 /**
12  * Tests media source plugins related logic.
13  *
14  * @group media
15  */
16 class MediaSourceTest extends MediaKernelTestBase {
17
18   /**
19    * Tests that metadata is correctly mapped irrespective of how media is saved.
20    */
21   public function testSave() {
22     $field_storage = FieldStorageConfig::create([
23       'entity_type' => 'media',
24       'field_name' => 'field_to_map_to',
25       'type' => 'string',
26     ]);
27     $field_storage->save();
28
29     FieldConfig::create([
30       'field_storage' => $field_storage,
31       'bundle' => $this->testMediaType->id(),
32       'label' => 'Field to map to',
33     ])->save();
34
35     // Set an arbitrary metadata value to be mapped.
36     $this->container->get('state')
37       ->set('media_source_test_attributes', [
38         'attribute_to_map' => [
39           'title' => 'Attribute to map',
40           'value' => 'Snowball',
41         ],
42         'thumbnail_uri' => [
43           'value' => 'public://TheSisko.png',
44         ],
45       ]);
46     $this->testMediaType->setFieldMap([
47       'attribute_to_map' => 'field_to_map_to',
48     ])->save();
49
50     /** @var \Drupal\Core\Entity\EntityStorageInterface $storage */
51     $storage = $this->container->get('entity_type.manager')
52       ->getStorage('media');
53
54     /** @var \Drupal\media\MediaInterface $a */
55     $a = $storage->create([
56       'bundle' => $this->testMediaType->id(),
57     ]);
58     /** @var \Drupal\media\MediaInterface $b */
59     $b = $storage->create([
60       'bundle' => $this->testMediaType->id(),
61     ]);
62
63     // Set a random source value on both items.
64     $a->set($a->getSource()->getSourceFieldDefinition($a->bundle->entity)->getName(), $this->randomString());
65     $b->set($b->getSource()->getSourceFieldDefinition($b->bundle->entity)->getName(), $this->randomString());
66
67     $a->save();
68     $storage->save($b);
69
70     // Assert that the default name was mapped into the name field for both
71     // media items.
72     $this->assertFalse($a->get('name')->isEmpty());
73     $this->assertFalse($b->get('name')->isEmpty());
74
75     // Assert that arbitrary metadata was mapped correctly.
76     $this->assertFalse($a->get('field_to_map_to')->isEmpty());
77     $this->assertFalse($b->get('field_to_map_to')->isEmpty());
78
79     // Assert that the thumbnail was mapped correctly from the source.
80     $this->assertSame('public://TheSisko.png', $a->thumbnail->entity->getFileUri());
81     $this->assertSame('public://TheSisko.png', $b->thumbnail->entity->getFileUri());
82   }
83
84   /**
85    * Tests default media name functionality.
86    */
87   public function testDefaultName() {
88     // Make sure that the default name is set if not provided by the user.
89     /** @var \Drupal\media\MediaInterface $media */
90     $media = Media::create(['bundle' => $this->testMediaType->id()]);
91     $media_source = $media->getSource();
92     $this->assertSame('default_name', $media_source->getPluginDefinition()['default_name_metadata_attribute'], 'Default metadata attribute is not used for the default name.');
93     $this->assertSame('media:' . $media->bundle() . ':' . $media->uuid(), $media_source->getMetadata($media, 'default_name'), 'Value of the default name metadata attribute does not look correct.');
94     $this->assertSame('media:' . $media->bundle() . ':' . $media->uuid(), $media->getName(), 'Default name was not used correctly by getName().');
95     $this->assertSame($media->getName(), $media->label(), 'Default name and label are not the same.');
96     $media->save();
97     $this->assertSame('media:' . $media->bundle() . ':' . $media->uuid(), $media->getName(), 'Default name was not saved correctly.');
98     $this->assertSame($media->getName(), $media->label(), 'The label changed during save.');
99
100     // Make sure that the user-supplied name is used.
101     /** @var \Drupal\media\MediaInterface $media */
102     $name = 'User-supplied name';
103     $media = Media::create([
104       'bundle' => $this->testMediaType->id(),
105       'name' => $name,
106     ]);
107     $media_source = $media->getSource();
108     $this->assertSame('default_name', $media_source->getPluginDefinition()['default_name_metadata_attribute'], 'Default metadata attribute is not used for the default name.');
109     $this->assertSame('media:' . $media->bundle() . ':' . $media->uuid(), $media_source->getMetadata($media, 'default_name'), 'Value of the default name metadata attribute does not look correct.');
110     $media->save();
111     $this->assertSame($name, $media->getName(), 'User-supplied name was not set correctly.');
112     $this->assertSame($media->getName(), $media->label(), 'The user-supplied name does not match the label.');
113
114     // Change the default name attribute and see if it is used to set the name.
115     $name = 'Old Major';
116     \Drupal::state()->set('media_source_test_attributes', ['alternative_name' => ['title' => 'Alternative name', 'value' => $name]]);
117     \Drupal::state()->set('media_source_test_definition', ['default_name_metadata_attribute' => 'alternative_name']);
118     /** @var \Drupal\media\MediaInterface $media */
119     $media = Media::create(['bundle' => $this->testMediaType->id()]);
120     $media_source = $media->getSource();
121     $this->assertSame('alternative_name', $media_source->getPluginDefinition()['default_name_metadata_attribute'], 'Correct metadata attribute is not used for the default name.');
122     $this->assertSame($name, $media_source->getMetadata($media, 'alternative_name'), 'Value of the default name metadata attribute does not look correct.');
123     $media->save();
124     $this->assertSame($name, $media->getName(), 'Default name was not set correctly.');
125     $this->assertSame($media->getName(), $media->label(), 'The default name does not match the label.');
126   }
127
128   /**
129    * Tests metadata mapping functionality.
130    */
131   public function testMetadataMapping() {
132     $field_name = 'field_to_map_to';
133     $attribute_name = 'attribute_to_map';
134     $storage = FieldStorageConfig::create([
135       'entity_type' => 'media',
136       'field_name' => $field_name,
137       'type' => 'string',
138     ]);
139     $storage->save();
140
141     FieldConfig::create([
142       'field_storage' => $storage,
143       'bundle' => $this->testMediaType->id(),
144       'label' => 'Field to map to',
145     ])->save();
146
147     // Save the entity without defining the metadata mapping and check that the
148     // field stays empty.
149     /** @var \Drupal\media\MediaInterface $media */
150     $media = Media::create([
151       'bundle' => $this->testMediaType->id(),
152       'field_media_test' => 'some_value',
153     ]);
154     $media->save();
155     $this->assertEmpty($media->get($field_name)->value, 'Field stayed empty.');
156
157     // Make sure that source plugin returns NULL for non-existing fields.
158     $this->testMediaType->setFieldMap(['not_here_at_all' => $field_name])->save();
159     $media = Media::create([
160       'bundle' => $this->testMediaType->id(),
161       'field_media_test' => 'some_value',
162     ]);
163     $media_source = $media->getSource();
164     $this->assertNull($media_source->getMetadata($media, 'not_here_at_all'), 'NULL is not returned if asking for a value of non-existing metadata.');
165     $media->save();
166     $this->assertTrue($media->get($field_name)->isEmpty(), 'Non-existing metadata attribute was wrongly mapped to the field.');
167
168     // Define mapping and make sure that the value was stored in the field.
169     \Drupal::state()->set('media_source_test_attributes', [
170       $attribute_name => ['title' => 'Attribute to map', 'value' => 'Snowball'],
171     ]);
172     $this->testMediaType->setFieldMap([$attribute_name => $field_name])->save();
173     $media = Media::create([
174       'bundle' => $this->testMediaType->id(),
175       'field_media_test' => 'some_value',
176     ]);
177     $media_source = $media->getSource();
178     $this->assertSame('Snowball', $media_source->getMetadata($media, $attribute_name), 'Value of the metadata attribute is not correct.');
179     $media->save();
180     $this->assertSame('Snowball', $media->get($field_name)->value, 'Metadata attribute was not mapped to the field.');
181
182     // Change the metadata attribute value and re-save the entity. Field value
183     // should stay the same.
184     \Drupal::state()->set('media_source_test_attributes', [
185       $attribute_name => ['title' => 'Attribute to map', 'value' => 'Pinkeye'],
186     ]);
187     $this->assertSame('Pinkeye', $media_source->getMetadata($media, $attribute_name), 'Value of the metadata attribute is not correct.');
188     $media->save();
189     $this->assertSame('Snowball', $media->get($field_name)->value, 'Metadata attribute was not mapped to the field.');
190
191     // Now change the value of the source field and make sure that the mapped
192     // values update too.
193     $this->assertSame('Pinkeye', $media_source->getMetadata($media, $attribute_name), 'Value of the metadata attribute is not correct.');
194     $media->set('field_media_test', 'some_new_value');
195     $media->save();
196     $this->assertSame('Pinkeye', $media->get($field_name)->value, 'Metadata attribute was not mapped to the field.');
197
198     // Remove the value of the mapped field and make sure that it is re-mapped
199     // on save.
200     \Drupal::state()->set('media_source_test_attributes', [
201       $attribute_name => ['title' => 'Attribute to map', 'value' => 'Snowball'],
202     ]);
203     $media->{$field_name}->value = NULL;
204     $this->assertSame('Snowball', $media_source->getMetadata($media, $attribute_name), 'Value of the metadata attribute is not correct.');
205     $media->save();
206     $this->assertSame('Snowball', $media->get($field_name)->value, 'Metadata attribute was not mapped to the field.');
207   }
208
209   /**
210    * Tests the getSourceFieldValue() method.
211    */
212   public function testGetSourceFieldValue() {
213     /** @var \Drupal\media\MediaInterface $media */
214     $media = Media::create([
215       'bundle' => $this->testMediaType->id(),
216       'field_media_test' => 'some_value',
217     ]);
218     $media->save();
219     $media_source = $media->getSource();
220     $this->assertSame('some_value', $media_source->getSourceFieldValue($media));
221   }
222
223   /**
224    * Tests the thumbnail functionality.
225    */
226   public function testThumbnail() {
227     file_put_contents('public://thumbnail1.jpg', '');
228     file_put_contents('public://thumbnail2.jpg', '');
229
230     // Save a media item and make sure thumbnail was added.
231     \Drupal::state()->set('media_source_test_attributes', [
232       'thumbnail_uri' => ['value' => 'public://thumbnail1.jpg'],
233     ]);
234     /** @var \Drupal\media\MediaInterface $media */
235     $media = Media::create([
236       'bundle' => $this->testMediaType->id(),
237       'name' => 'Mr. Jones',
238       'field_media_test' => 'some_value',
239     ]);
240     $media_source = $media->getSource();
241     $this->assertSame('public://thumbnail1.jpg', $media_source->getMetadata($media, 'thumbnail_uri'), 'Value of the thumbnail metadata attribute is not correct.');
242     $media->save();
243     $this->assertSame('public://thumbnail1.jpg', $media->thumbnail->entity->getFileUri(), 'Thumbnail was not added to the media item.');
244     // We expect the title not to be present on the Thumbnail.
245     $this->assertEmpty($media->thumbnail->title);
246     $this->assertSame('', $media->thumbnail->alt);
247
248     // Now change the metadata attribute and make sure that the thumbnail stays
249     // the same.
250     \Drupal::state()->set('media_source_test_attributes', [
251       'thumbnail_uri' => ['value' => 'public://thumbnail2.jpg'],
252     ]);
253     $this->assertSame('public://thumbnail2.jpg', $media_source->getMetadata($media, 'thumbnail_uri'), 'Value of the thumbnail metadata attribute is not correct.');
254     $media->save();
255     $this->assertSame('public://thumbnail1.jpg', $media->thumbnail->entity->getFileUri(), 'Thumbnail was not preserved.');
256     $this->assertEmpty($media->thumbnail->title);
257     $this->assertSame('', $media->thumbnail->alt);
258
259     // Remove the thumbnail and make sure that it is auto-updated on save.
260     $media->thumbnail->target_id = NULL;
261     $this->assertSame('public://thumbnail2.jpg', $media_source->getMetadata($media, 'thumbnail_uri'), 'Value of the thumbnail metadata attribute is not correct.');
262     $media->save();
263     $this->assertSame('public://thumbnail2.jpg', $media->thumbnail->entity->getFileUri(), 'New thumbnail was not added to the media item.');
264     $this->assertEmpty($media->thumbnail->title);
265     $this->assertSame('', $media->thumbnail->alt);
266
267     // Change the metadata attribute again, change the source field value too
268     // and make sure that the thumbnail updates.
269     \Drupal::state()->set('media_source_test_attributes', [
270       'thumbnail_uri' => ['value' => 'public://thumbnail1.jpg'],
271     ]);
272     $media->field_media_test->value = 'some_new_value';
273     $this->assertSame('public://thumbnail1.jpg', $media_source->getMetadata($media, 'thumbnail_uri'), 'Value of the thumbnail metadata attribute is not correct.');
274     $media->save();
275     $this->assertSame('public://thumbnail1.jpg', $media->thumbnail->entity->getFileUri(), 'New thumbnail was not added to the media item.');
276     $this->assertEmpty($media->thumbnail->title);
277     $this->assertSame('', $media->thumbnail->alt);
278
279     // Change the thumbnail metadata attribute and make sure that the thumbnail
280     // is set correctly.
281     \Drupal::state()->set('media_source_test_attributes', [
282       'thumbnail_uri' => ['value' => 'public://thumbnail1.jpg'],
283       'alternative_thumbnail_uri' => ['value' => 'public://thumbnail2.jpg'],
284     ]);
285     \Drupal::state()->set('media_source_test_definition', ['thumbnail_uri_metadata_attribute' => 'alternative_thumbnail_uri']);
286     $media = Media::create([
287       'bundle' => $this->testMediaType->id(),
288       'name' => 'Mr. Jones',
289       'field_media_test' => 'some_value',
290     ]);
291     $media_source = $media->getSource();
292     $this->assertSame('public://thumbnail1.jpg', $media_source->getMetadata($media, 'thumbnail_uri'), 'Value of the metadata attribute is not correct.');
293     $this->assertSame('public://thumbnail2.jpg', $media_source->getMetadata($media, 'alternative_thumbnail_uri'), 'Value of the thumbnail metadata attribute is not correct.');
294     $media->save();
295     $this->assertSame('public://thumbnail2.jpg', $media->thumbnail->entity->getFileUri(), 'Correct metadata attribute was not used for the thumbnail.');
296     $this->assertEmpty($media->thumbnail->title);
297     $this->assertSame('', $media->thumbnail->alt);
298
299     // Enable queued thumbnails and make sure that the entity gets the default
300     // thumbnail initially.
301     \Drupal::state()->set('media_source_test_definition', []);
302     \Drupal::state()->set('media_source_test_attributes', [
303       'thumbnail_uri' => ['value' => 'public://thumbnail1.jpg'],
304     ]);
305     $this->testMediaType->setQueueThumbnailDownloadsStatus(TRUE)->save();
306     $media = Media::create([
307       'bundle' => $this->testMediaType->id(),
308       'name' => 'Mr. Jones',
309       'field_media_test' => 'some_value',
310     ]);
311     $this->assertSame('public://thumbnail1.jpg', $media->getSource()->getMetadata($media, 'thumbnail_uri'), 'Value of the metadata attribute is not correct.');
312     $media->save();
313     $this->assertSame('public://media-icons/generic/generic.png', $media->thumbnail->entity->getFileUri(), 'Default thumbnail was not set initially.');
314     $this->assertEmpty($media->thumbnail->title);
315     $this->assertSame('', $media->thumbnail->alt);
316
317     // Process the queue item and make sure that the thumbnail was updated too.
318     $queue_name = 'media_entity_thumbnail';
319     /** @var \Drupal\Core\Queue\QueueWorkerInterface $queue_worker */
320     $queue_worker = \Drupal::service('plugin.manager.queue_worker')->createInstance($queue_name);
321     $queue = \Drupal::queue($queue_name);
322     $this->assertSame(1, $queue->numberOfItems(), 'Item was not added to the queue.');
323
324     $item = $queue->claimItem();
325     $this->assertSame($media->id(), $item->data['id'], 'Queue item that was created does not belong to the correct entity.');
326
327     $queue_worker->processItem($item->data);
328     $queue->deleteItem($item);
329     $this->assertSame(0, $queue->numberOfItems(), 'Item was not removed from the queue.');
330
331     $media = Media::load($media->id());
332     $this->assertSame('public://thumbnail1.jpg', $media->thumbnail->entity->getFileUri(), 'Thumbnail was not updated by the queue.');
333     $this->assertEmpty($media->thumbnail->title);
334     $this->assertSame('', $media->thumbnail->alt);
335
336     // Set the alt metadata attribute and make sure it's used for the thumbnail.
337     \Drupal::state()->set('media_source_test_definition', [
338       'thumbnail_alt_metadata_attribute' => 'alt',
339     ]);
340     \Drupal::state()->set('media_source_test_attributes', [
341       'alt' => ['value' => 'This will be alt.'],
342     ]);
343     $media = Media::create([
344       'bundle' => $this->testMediaType->id(),
345       'name' => 'Boxer',
346       'field_media_test' => 'some_value',
347     ]);
348     $media->save();
349     $this->assertSame('Boxer', $media->getName(), 'Correct name was not set on the media item.');
350     $this->assertEmpty($media->thumbnail->title);
351     $this->assertSame('This will be alt.', $media->thumbnail->alt);
352   }
353
354   /**
355    * Tests the media item constraints functionality.
356    */
357   public function testConstraints() {
358     // Test entity constraints.
359     \Drupal::state()->set('media_source_test_entity_constraints', [
360       'MediaTestConstraint' => [],
361     ]);
362
363     // Create a media item media that uses a source plugin with constraints and
364     // make sure the constraints works as expected when validating.
365     /** @var \Drupal\media\MediaInterface $media */
366     $media = Media::create([
367       'bundle' => $this->testConstraintsMediaType->id(),
368       'name' => 'I do not like Drupal',
369       'field_media_test_constraints' => 'Not checked',
370     ]);
371
372     // Validate the entity and make sure violation is reported.
373     /** @var \Drupal\Core\Entity\EntityConstraintViolationListInterface $violations */
374     $violations = $media->validate();
375     $this->assertCount(1, $violations, 'Expected number of validations not found.');
376     $this->assertEquals('Inappropriate text.', $violations->get(0)->getMessage(), 'Incorrect constraint validation message found.');
377
378     // Fix the violation and make sure it is not reported anymore.
379     $media->setName('I love Drupal!');
380     $violations = $media->validate();
381     $this->assertCount(0, $violations, 'Expected number of validations not found.');
382
383     // Save and make sure it succeeded.
384     $this->assertEmpty($media->id(), 'Entity ID was found.');
385     $media->save();
386     $this->assertNotEmpty($media->id(), 'Entity ID was not found.');
387     $this->assertSame($media->getName(), 'I love Drupal!');
388
389     // Test source field constraints.
390     \Drupal::state()->set('media_source_test_field_constraints', [
391       'MediaTestConstraint' => [],
392     ]);
393     \Drupal::state()->set('media_source_test_entity_constraints', []);
394
395     // Create media that uses source with constraints and make sure it can't
396     // be saved without validating them.
397     /** @var \Drupal\media\MediaInterface $media */
398     $media = Media::create([
399       'bundle' => $this->testConstraintsMediaType->id(),
400       'name' => 'Not checked',
401       'field_media_test_constraints' => 'I do not like Drupal',
402     ]);
403
404     // Validate the entity and make sure violation is reported.
405     /** @var \Drupal\Core\Entity\EntityConstraintViolationListInterface $violations */
406     $violations = $media->validate();
407     $this->assertCount(1, $violations, 'Expected number of validations not found.');
408     $this->assertEquals('Inappropriate text.', $violations->get(0)->getMessage(), 'Incorrect constraint validation message found.');
409
410     // Fix the violation and make sure it is not reported anymore.
411     $media->set('field_media_test_constraints', 'I love Drupal!');
412     $violations = $media->validate();
413     $this->assertCount(0, $violations, 'Expected number of validations not found.');
414
415     // Save and make sure it succeeded.
416     $this->assertEmpty($media->id(), 'Entity ID was found.');
417     $media->save();
418     $this->assertNotEmpty($media->id(), 'Entity ID was not found.');
419   }
420
421   /**
422    * Tests logic related to the automated source field creation.
423    */
424   public function testSourceFieldCreation() {
425     /** @var \Drupal\media\MediaTypeInterface $type */
426     $type = MediaType::create([
427       'id' => 'test_type',
428       'label' => 'Test type',
429       'source' => 'test',
430     ]);
431
432     /** @var \Drupal\field\Entity\FieldConfig $field */
433     $field = $type->getSource()->createSourceField($type);
434     /** @var \Drupal\field\Entity\FieldStorageConfig $field_storage */
435     $field_storage = $field->getFieldStorageDefinition();
436
437     // Test field storage.
438     $this->assertTrue($field_storage->isNew(), 'Field storage is saved automatically.');
439     $this->assertFalse($field_storage->isLocked(), 'Field storage is not locked.');
440     $this->assertSame('string', $field_storage->getType(), 'Field is not of correct type.');
441     $this->assertSame('field_media_test_1', $field_storage->getName(), 'Incorrect field name is used.');
442     $this->assertSame('media', $field_storage->getTargetEntityTypeId(), 'Field is not targeting media entities.');
443
444     // Test field.
445     $this->assertTrue($field->isNew(), 'Field is saved automatically.');
446     $this->assertSame('field_media_test_1', $field->getName(), 'Incorrect field name is used.');
447     $this->assertSame('string', $field->getType(), 'Field is of incorrect type.');
448     $this->assertTrue($field->isRequired(), 'Field is not required.');
449     $this->assertEquals('Test source', $field->label(), 'Incorrect label is used.');
450     $this->assertSame('test_type', $field->getTargetBundle(), 'Field is not targeting correct bundle.');
451
452     // Fields should be automatically saved only when creating the media type
453     // using the media type creation form. Make sure that they are not saved
454     // when creating a media type programmatically.
455     // Drupal\Tests\media\FunctionalJavascript\MediaTypeCreationTest is testing
456     // form part of the functionality.
457     $type->save();
458     $storage = FieldStorageConfig::load('media.field_media_test_1');
459     $this->assertNull($storage, 'Field storage was not saved.');
460     $field = FieldConfig::load('media.test_type.field_media_test_1');
461     $this->assertNull($field, 'Field storage was not saved.');
462
463     // Test the plugin with a different default source field type.
464     $type = MediaType::create([
465       'id' => 'test_constraints_type',
466       'label' => 'Test type with constraints',
467       'source' => 'test_constraints',
468     ]);
469     $field = $type->getSource()->createSourceField($type);
470     $field_storage = $field->getFieldStorageDefinition();
471
472     // Test field storage.
473     $this->assertTrue($field_storage->isNew(), 'Field storage is saved automatically.');
474     $this->assertFalse($field_storage->isLocked(), 'Field storage is not locked.');
475     $this->assertSame('string_long', $field_storage->getType(), 'Field is of incorrect type.');
476     $this->assertSame('field_media_test_constraints_1', $field_storage->getName(), 'Incorrect field name is used.');
477     $this->assertSame('media', $field_storage->getTargetEntityTypeId(), 'Field is not targeting media entities.');
478
479     // Test field.
480     $this->assertTrue($field->isNew(), 'Field is saved automatically.');
481     $this->assertSame('field_media_test_constraints_1', $field->getName(), 'Incorrect field name is used.');
482     $this->assertSame('string_long', $field->getType(), 'Field is of incorrect type.');
483     $this->assertTrue($field->isRequired(), 'Field is not required.');
484     $this->assertEquals('Test source with constraints', $field->label(), 'Incorrect label is used.');
485     $this->assertSame('test_constraints_type', $field->getTargetBundle(), 'Field is not targeting correct bundle.');
486   }
487
488   /**
489    * Tests configuration form submit handler on the base media source plugin.
490    */
491   public function testSourceConfigurationSubmit() {
492     /** @var \Drupal\media\MediaSourceManager $manager */
493     $manager = $this->container->get('plugin.manager.media.source');
494     $form = [];
495     $form_state = new FormState();
496     $form_state->setValues(['test_config_value' => 'Somewhere over the rainbow.']);
497
498     /** @var \Drupal\media\MediaSourceInterface $source */
499     $source = $manager->createInstance('test', []);
500     $source->submitConfigurationForm($form, $form_state);
501     $expected = ['source_field' => 'field_media_test_1', 'test_config_value' => 'Somewhere over the rainbow.'];
502     $this->assertSame($expected, $source->getConfiguration(), 'Submitted values were saved correctly.');
503
504     // Try to save a NULL value.
505     $form_state->setValue('test_config_value', NULL);
506     $source->submitConfigurationForm($form, $form_state);
507     $expected['test_config_value'] = NULL;
508     $this->assertSame($expected, $source->getConfiguration(), 'Submitted values were saved correctly.');
509
510     // Make sure that the config keys are determined correctly even if the
511     // existing value is NULL.
512     $form_state->setValue('test_config_value', 'Somewhere over the rainbow.');
513     $source->submitConfigurationForm($form, $form_state);
514     $expected['test_config_value'] = 'Somewhere over the rainbow.';
515     $this->assertSame($expected, $source->getConfiguration(), 'Submitted values were saved correctly.');
516
517     // Make sure that a non-relevant value will be skipped.
518     $form_state->setValue('not_relevant', 'Should not be saved in the plugin.');
519     $source->submitConfigurationForm($form, $form_state);
520     $this->assertSame($expected, $source->getConfiguration(), 'Submitted values were saved correctly.');
521   }
522
523   /**
524    * Tests different display options for the source field.
525    */
526   public function testDifferentSourceFieldDisplays() {
527     $id = 'test_different_displays';
528     $field_name = 'field_media_different_display';
529
530     $this->createMediaTypeViaForm($id, $field_name);
531
532     // Source field not in displays.
533     $display = entity_get_display('media', $id, 'default');
534     $components = $display->getComponents();
535     $this->assertArrayHasKey($field_name, $components);
536     $this->assertSame('entity_reference_entity_id', $components[$field_name]['type']);
537
538     $display = entity_get_form_display('media', $id, 'default');
539     $components = $display->getComponents();
540     $this->assertArrayHasKey($field_name, $components);
541     $this->assertSame('entity_reference_autocomplete_tags', $components[$field_name]['type']);
542   }
543
544   /**
545    * Tests hidden source field in media type.
546    */
547   public function testHiddenSourceField() {
548     $id = 'test_hidden_source_field';
549     $field_name = 'field_media_hidden';
550
551     $this->createMediaTypeViaForm($id, $field_name);
552
553     // Source field not in displays.
554     $display = entity_get_display('media', $id, 'default');
555     $this->assertArrayNotHasKey($field_name, $display->getComponents());
556
557     $display = entity_get_form_display('media', $id, 'default');
558     $this->assertArrayNotHasKey($field_name, $display->getComponents());
559   }
560
561   /**
562    * Creates a media type via form submit.
563    *
564    * @param string $source_plugin_id
565    *   Source plugin ID.
566    * @param string $field_name
567    *   Source field name.
568    */
569   protected function createMediaTypeViaForm($source_plugin_id, $field_name) {
570     /** @var \Drupal\media\MediaTypeInterface $type */
571     $type = MediaType::create(['source' => $source_plugin_id]);
572
573     $form = $this->container->get('entity_type.manager')
574       ->getFormObject('media_type', 'add')
575       ->setEntity($type);
576
577     $form_state = new FormState();
578     $form_state->setValues([
579       'label' => 'Test type',
580       'id' => $source_plugin_id,
581       'op' => t('Save'),
582     ]);
583
584     /** @var \Drupal\Core\Entity\EntityFieldManagerInterface $field_manager */
585     $field_manager = \Drupal::service('entity_field.manager');
586
587     // Source field not created yet.
588     $fields = $field_manager->getFieldDefinitions('media', $source_plugin_id);
589     $this->assertArrayNotHasKey($field_name, $fields);
590
591     \Drupal::formBuilder()->submitForm($form, $form_state);
592
593     // Source field exists now.
594     $fields = $field_manager->getFieldDefinitions('media', $source_plugin_id);
595     $this->assertArrayHasKey($field_name, $fields);
596   }
597
598 }