3 namespace Drupal\Tests\media\Traits;
5 use Drupal\media\Entity\MediaType;
8 * Provides methods to create a media type from given values.
10 * This trait is meant to be used only by test classes.
12 trait MediaTypeCreationTrait {
15 * Create a media type for a source plugin.
17 * @param string $source_plugin_id
18 * The media source plugin ID.
19 * @param mixed[] $values
20 * (optional) Additional values for the media type entity:
21 * - id: The ID of the media type. If none is provided, a random value will
23 * - label: The human-readable label of the media type. If none is provided,
24 * a random value will be used.
25 * - bundle: (deprecated) The ID of the media type, for backwards
26 * compatibility purposes. Use 'id' instead.
27 * See \Drupal\media\MediaTypeInterface and \Drupal\media\Entity\MediaType
28 * for full documentation of the media type properties.
30 * @return \Drupal\media\MediaTypeInterface
33 * @see \Drupal\media\MediaTypeInterface
34 * @see \Drupal\media\Entity\MediaType
36 protected function createMediaType($source_plugin_id, array $values = []) {
37 if (isset($values['bundle'])) {
38 @trigger_error('Setting the "bundle" key when creating a test media type is deprecated in Drupal 8.6.0 and will be removed before Drupal 9.0.0. Set the "id" key instead. See https://www.drupal.org/node/2981614.', E_USER_DEPRECATED);
39 $values['id'] = $values['bundle'];
40 unset($values['bundle']);
44 'id' => $this->randomMachineName(),
45 'label' => $this->randomString(),
46 'source' => $source_plugin_id,
49 /** @var \Drupal\media\MediaTypeInterface $media_type */
50 $media_type = MediaType::create($values);
51 $this->assertSame(SAVED_NEW, $media_type->save());
53 $source = $media_type->getSource();
54 $source_field = $source->createSourceField($media_type);
55 // The media type form creates a source field if it does not exist yet. The
56 // same must be done in a kernel test, since it does not use that form.
57 // @see \Drupal\media\MediaTypeForm::save()
58 $source_field->getFieldStorageDefinition()->save();
59 // The source field storage has been created, now the field can be saved.
60 $source_field->save();
62 $source_configuration = $source->getConfiguration();
63 $source_configuration['source_field'] = $source_field->getName();
64 $source->setConfiguration($source_configuration);
66 $this->assertSame(SAVED_UPDATED, $media_type->save());
68 // Add the source field to the form display for the media type.
69 $form_display = entity_get_form_display('media', $media_type->id(), 'default');
70 $source->prepareFormDisplay($media_type, $form_display);
71 $form_display->save();