You are here

protected function DownloadController::getFile in Media Download 1.0.x

Same name and namespace in other branches
  1. 1.2.x src/DownloadController.php \Drupal\media_download\DownloadController::getFile()
  2. 1.1.x src/DownloadController.php \Drupal\media_download\DownloadController::getFile()

Attempt to retrieve a file from the supplied media.

This method will only return a file if all of the following conditions are satisfied by the supplied media entity:

1. A source field can be determined 2. The source field exists on the supplied media entity 3. At least one field delta references a file that exists on disk

Return value

\Drupal\file\FileInterface|null A file on success, otherwise NULL.

Throws

\RuntimeException If the supplied media entity is NULL, or has no source field.

1 call to DownloadController::getFile()
DownloadController::save in src/DownloadController.php
Download the primary file resource referenced by the supplied media entity.

File

src/DownloadController.php, line 41

Class

DownloadController
Adds support for direct downloads of media entities.

Namespace

Drupal\media_download

Code

protected function getFile(MediaInterface $media) {

  // Ensure that the source field can be determined for this media.
  if (!isset($media) || empty($source_field = $media
    ->getSource()
    ->getConfiguration()['source_field'] ?? NULL) || !$media
    ->hasField($source_field)) {
    throw new \RuntimeException("No source field available for the requested entity.");
  }

  // Attempt to locate a valid file in the source field.
  foreach ($media->{$source_field} as $item) {

    // Skip this field item if it doesn't reference a file entity.
    if (!$item->entity instanceof FileInterface) {
      continue;
    }

    // Skip this field item if the referenced file doesn't exist.
    if (!file_exists($item->entity
      ->getFileUri())) {
      continue;
    }
    return $item->entity;
  }
  return NULL;
}