You are here

public static function MediaHelper::useFile in Varbase Media 9.0.x

Same name and namespace in other branches
  1. 8.7 modules/entity_browser_generic_embed/src/MediaHelper.php \Drupal\entity_browser_generic_embed\MediaHelper::useFile()
  2. 8.5 modules/entity_browser_generic_embed/src/MediaHelper.php \Drupal\entity_browser_generic_embed\MediaHelper::useFile()
  3. 8.6 modules/entity_browser_generic_embed/src/MediaHelper.php \Drupal\entity_browser_generic_embed\MediaHelper::useFile()

Attaches a file entity to a media entity.

Parameters

\Drupal\media\MediaInterface $entity: The media entity.

\Drupal\file\FileInterface $file: The file entity.

int $replace: (optional) What to do if the file already exists. Can be any of the constants accepted by file_move().

Return value

\Drupal\file\FileInterface|false The final file entity (unsaved), or FALSE if an error occurred.

File

modules/entity_browser_generic_embed/src/MediaHelper.php, line 151

Class

MediaHelper
Provides helper methods for dealing with media entities.

Namespace

Drupal\entity_browser_generic_embed

Code

public static function useFile(MediaInterface $entity, FileInterface $file, $replace = FileSystemInterface::EXISTS_RENAME) {
  $field = static::getSourceField($entity);
  $field
    ->setValue($file);
  $destination = '';
  $destination .= static::prepareFileDestination($entity);
  if (substr($destination, -1) != '/') {
    $destination .= '/';
  }
  $destination .= $file
    ->getFilename();
  if ($destination == $file
    ->getFileUri()) {
    return $file;
  }
  else {
    $file = file_move($file, $destination, $replace);
    if ($file) {
      $field
        ->setValue($file);
      return $file;
    }
    else {
      return FALSE;
    }
  }
}