You are here

public static function MediaHelper::useFile in Lightning Media 8

Same name and namespace in other branches
  1. 8.4 src/MediaHelper.php \Drupal\lightning_media\MediaHelper::useFile()
  2. 8.2 src/MediaHelper.php \Drupal\lightning_media\MediaHelper::useFile()
  3. 8.3 src/MediaHelper.php \Drupal\lightning_media\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.

2 calls to MediaHelper::useFile()
BulkUploadForm::submitForm in modules/lightning_media_bulk_upload/src/Form/BulkUploadForm.php
Form submission handler.
FileUpload::submit in src/Plugin/EntityBrowser/Widget/FileUpload.php

File

src/MediaHelper.php, line 148

Class

MediaHelper
Provides helper methods for dealing with media entities.

Namespace

Drupal\lightning_media

Code

public static function useFile(MediaInterface $entity, FileInterface $file, $replace = FILE_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;
    }
  }
}