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