summaryrefslogtreecommitdiffstats
path: root/core/modules/media/tests/src/Functional/MediaFunctionalTestCreateMediaTypeTrait.php
blob: 2d60c9bff611d43a816a8be4fb07ba012a3d46ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php

namespace Drupal\Tests\media\Functional;

use Drupal\media\Entity\MediaType;

/**
 * Trait with helpers for Media functional tests.
 */
trait MediaFunctionalTestCreateMediaTypeTrait {

  /**
   * Creates a media type.
   *
   * @param array $values
   *   The media type values.
   * @param string $source
   *   (optional) The media source plugin that is responsible for additional
   *   logic related to this media type. Defaults to 'test'.
   *
   * @return \Drupal\media\MediaTypeInterface
   *   A newly created media type.
   */
  protected function createMediaType(array $values = [], $source = 'test') {
    if (empty($values['bundle'])) {
      $id = strtolower($this->randomMachineName());
    }
    else {
      $id = $values['bundle'];
    }
    $values += [
      'id' => $id,
      'label' => $id,
      'source' => $source,
      'source_configuration' => [],
      'field_map' => [],
      'new_revision' => FALSE,
    ];

    $media_type = MediaType::create($values);
    $status = $media_type->save();

    // @todo Rename to assertSame() when #1945040 is done.
    // @see https://www.drupal.org/node/1945040
    $this->assertIdentical(SAVED_NEW, $status, 'Media type was created successfully.');

    // Ensure that the source field exists.
    $source = $media_type->getSource();
    $source_field = $source->getSourceFieldDefinition($media_type);
    if (!$source_field) {
      $source_field = $source->createSourceField($media_type);
      /** @var \Drupal\field\FieldStorageConfigInterface $storage */
      $storage = $source_field->getFieldStorageDefinition();
      $storage->setLocked(TRUE)->save();
      $source_field->save();

      $media_type
        ->set('source_configuration', [
          'source_field' => $source_field->getName(),
        ])
        ->save();
    }

    return $media_type;
  }

}