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;
      }
    }
  }
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;
      }
    }
  }
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 ; } } }
Attaches a file entity to a media entity.

@param \Drupal\media\MediaInterface $entity
The media entity.
@param \Drupal\file\FileInterface $file
The file entity.
@param int $replace
(optional) What to do if the file already exists. Can be any of the
constants accepted by file_move().

@return \Drupal\file\FileInterface|false
The final file entity (unsaved), or FALSE if an error occurred.
Attaches a file entity to a media entity .