You are here

public function SchedulerMediaSetupTrait::getMediaItem in Scheduler 2.x

Gets a media item from storage.

For nodes, there is drupalGetNodeByTitle() but nothing similar exists to help Media testing. But this function goes one better - if a name is given, then a match will be attempted on the name, and fail if none found. But if no name is supplied then the media entity with the highest id value (the newest item created) is returned, as this is often what is required.

Parameters

string $name: Optional name text to match on. If given and no match, returns NULL. If no $name is given then returns the media with the highest id value.

Return value

\Drupal\media\MediaInterface The media object.

File

tests/src/Traits/SchedulerMediaSetupTrait.php, line 172

Class

SchedulerMediaSetupTrait
Additional setup trait for Scheduler tests that use Media.

Namespace

Drupal\Tests\scheduler\Traits

Code

public function getMediaItem(string $name = NULL) {
  $query = $this->mediaStorage
    ->getQuery()
    ->accessCheck(FALSE)
    ->sort('mid', 'DESC');
  if (!empty($name)) {
    $query
      ->condition('name', $name);
  }
  $result = $query
    ->execute();
  if (count($result)) {
    $media_id = reset($result);
    return $this->mediaStorage
      ->load($media_id);
  }
  else {
    return NULL;
  }
}