You are here

protected function MediaTest::createEntity in JSON:API 8

Same name and namespace in other branches
  1. 8.2 tests/src/Functional/MediaTest.php \Drupal\Tests\jsonapi\Functional\MediaTest::createEntity()

Creates the entity to be tested.

Return value

\Drupal\Core\Entity\EntityInterface The entity to be tested.

Overrides ResourceTestBase::createEntity

File

tests/src/Functional/MediaTest.php, line 93

Class

MediaTest
JSON API integration test for the "Media" content entity type.

Namespace

Drupal\Tests\jsonapi\Functional

Code

protected function createEntity() {
  if (!MediaType::load('camelids')) {

    // Create a "Camelids" media type.
    $media_type = MediaType::create([
      'name' => 'Camelids',
      'id' => 'camelids',
      'description' => 'Camelids are large, strictly herbivorous animals with slender necks and long legs.',
      'source' => 'file',
    ]);
    $media_type
      ->save();

    // Create the source field.
    $source_field = $media_type
      ->getSource()
      ->createSourceField($media_type);
    $source_field
      ->getFieldStorageDefinition()
      ->save();
    $source_field
      ->save();
    $media_type
      ->set('source_configuration', [
      'source_field' => $source_field
        ->getName(),
    ])
      ->save();
  }

  // Create a file to upload.
  $file = File::create([
    'uri' => 'public://llama.txt',
  ]);
  $file
    ->setPermanent();
  $file
    ->save();

  // @see \Drupal\Tests\jsonapi\Functional\MediaTest::testPostIndividual()
  $post_file = File::create([
    'uri' => 'public://llama2.txt',
  ]);
  $post_file
    ->setPermanent();
  $post_file
    ->save();

  // Create a "Llama" media item.
  // @todo Remove this modification when JSON API requires Drupal 8.5 or newer, and do an early return above instead.
  $file_field_name = floatval(\Drupal::VERSION) >= 8.5 ? 'field_media_file' : 'field_media_file_1';
  $media = Media::create([
    'bundle' => 'camelids',
    $file_field_name => [
      'target_id' => $file
        ->id(),
    ],
  ]);
  $media
    ->setName('Llama')
    ->setPublished(TRUE)
    ->setCreatedTime(123456789)
    ->setOwnerId($this->account
    ->id())
    ->setRevisionUserId($this->account
    ->id())
    ->save();
  return $media;
}