public static function MediaHelper::useFile in Lightning Media 8.3
Same name and namespace in other branches
- 8.4 src/MediaHelper.php \Drupal\lightning_media\MediaHelper::useFile()
- 8 src/MediaHelper.php \Drupal\lightning_media\MediaHelper::useFile()
- 8.2 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(). Defaults to \Drupal\Core\File\FileSystemInterface::EXISTS_RENAME.
Return value
\Drupal\file\FileInterface|false The final file entity (unsaved), or FALSE if an error occurred.
3 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 - MediaHelperTest::testUseFile in tests/
src/ Kernel/ MediaHelperTest.php - @covers ::getSourceField @covers ::prepareFileDestination @covers ::useFile
File
- src/
MediaHelper.php, line 172
Class
- MediaHelper
- Provides helper methods for dealing with media entities.
Namespace
Drupal\lightning_mediaCode
public static function useFile(MediaInterface $entity, FileInterface $file, $replace = NULL) {
// @todo Remove this and just use FileSystemInterface::EXISTS_REPLACE when support for older versions of core is dropped.
if (is_null($replace)) {
$replace = defined(FileSystemInterface::class . '::EXISTS_RENAME') ? FileSystemInterface::EXISTS_RENAME : constant('FILE_EXISTS_RENAME');
}
$field = static::getSourceField($entity);
$field
->setValue($file);
$destination = '';
$destination .= static::prepareFileDestination($entity);
if (substr($destination, -1) != '/') {
$destination .= '/';
}
$destination .= $file
->getFilename();
// If the core file_move() function has already been called, the file entity
// might have been replaced by another one that has the same ID, but a
// different URI. So reload the file entity to ensure we're using the most
// up-to-date URI.
/** @var \Drupal\file\FileInterface $file */
$file = File::load($file
->id());
if ($destination == $file
->getFileUri()) {
return $file;
}
else {
$file = file_move($file, $destination, $replace);
if ($file) {
$field
->setValue($file);
return $file;
}
else {
return FALSE;
}
}
}