4197caab65c8f61e04c35beea2ef59210c056423
[yaffs-website] / web / core / modules / media / tests / src / Functional / MediaFunctionalTestCreateMediaTypeTrait.php
1 <?php
2
3 namespace Drupal\Tests\media\Functional;
4
5 use Drupal\media\Entity\MediaType;
6
7 /**
8  * Trait with helpers for Media functional tests.
9  */
10 trait MediaFunctionalTestCreateMediaTypeTrait {
11
12   /**
13    * Creates a media type.
14    *
15    * @param array $values
16    *   The media type values.
17    * @param string $source
18    *   (optional) The media source plugin that is responsible for additional
19    *   logic related to this media type. Defaults to 'test'.
20    *
21    * @return \Drupal\media\MediaTypeInterface
22    *   A newly created media type.
23    */
24   protected function createMediaType(array $values = [], $source = 'test') {
25     if (empty($values['bundle'])) {
26       $id = strtolower($this->randomMachineName());
27     }
28     else {
29       $id = $values['bundle'];
30     }
31     $values += [
32       'id' => $id,
33       'label' => $id,
34       'source' => $source,
35       'source_configuration' => [],
36       'field_map' => [],
37       'new_revision' => FALSE,
38     ];
39
40     $media_type = MediaType::create($values);
41     $status = $media_type->save();
42
43     // @todo Rename to assertSame() when #1945040 is done.
44     // @see https://www.drupal.org/node/1945040
45     $this->assertIdentical(SAVED_NEW, $status, 'Media type was created successfully.');
46
47     // Ensure that the source field exists.
48     $source = $media_type->getSource();
49     $source_field = $source->getSourceFieldDefinition($media_type);
50     if (!$source_field) {
51       $source_field = $source->createSourceField($media_type);
52       /** @var \Drupal\field\FieldStorageConfigInterface $storage */
53       $storage = $source_field->getFieldStorageDefinition();
54       $storage->save();
55       $source_field->save();
56
57       $media_type
58         ->set('source_configuration', [
59           'source_field' => $source_field->getName(),
60         ])
61         ->save();
62     }
63
64     return $media_type;
65   }
66
67 }