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