function FileRepository::move
Same name and namespace in other branches
- 10 core/modules/file/src/FileRepository.php \Drupal\file\FileRepository::move()
- 11.x core/modules/file/src/FileRepository.php \Drupal\file\FileRepository::move()
Moves a file to a new location and update the file's database entry.
- Checks if $source and $destination are valid and readable/writable.
- Performs a file move if $source is not equal to $destination.
- If file already exists in $destination either the call will error out, replace the file or rename the file based on the $replace parameter.
- Adds the new file to the files database.
Parameters
\Drupal\file\FileInterface $source: A file entity.
string $destination: A string containing the destination that $source should be moved to. This must be a stream wrapper URI.
int $replace: (optional) The replace behavior when the destination file already exists. Possible values include:
- FileSystemInterface::EXISTS_RENAME: (default) Append _{incrementing number} until the filename is unique.
- FileSystemInterface::EXISTS_REPLACE: Replace the existing file. If a managed file with the destination name exists then its database entry will be updated and $source->delete() called after invoking hook_file_move(). If no database entry is found, then the source files record will be updated.
- FileSystemInterface::EXISTS_ERROR: Do nothing and throw a \Drupal\Core\File\Exception\FileExistsException.
Return value
\Drupal\file\FileInterface The file entity.
Overrides FileRepositoryInterface::move
File
-
core/
modules/ file/ src/ FileRepository.php, line 167
Class
- FileRepository
- Provides a file entity repository.
Namespace
Drupal\fileCode
public function move(FileInterface $source, string $destination, int $replace = FileSystemInterface::EXISTS_RENAME) : FileInterface {
if (!$this->streamWrapperManager
->isValidUri($destination)) {
throw new InvalidStreamWrapperException("Invalid stream wrapper: {$destination}");
}
$uri = $this->fileSystem
->move($source->getFileUri(), $destination, $replace);
$delete_source = FALSE;
$file = clone $source;
$file->setFileUri($uri);
// If we are replacing an existing file re-use its database record.
if ($replace === FileSystemInterface::EXISTS_REPLACE) {
if ($existing = $this->loadByUri($uri)) {
$delete_source = TRUE;
$file->fid = $existing->id();
$file->uuid = $existing->uuid();
}
}
elseif ($replace === FileSystemInterface::EXISTS_RENAME && is_file($destination)) {
$file->setFilename($this->fileSystem
->basename($destination));
}
$file->save();
// Inform modules that the file has been moved.
$this->moduleHandler
->invokeAll('file_move', [
$file,
$source,
]);
// Delete the original if it's not in use elsewhere.
if ($delete_source && !$this->fileUsage
->listUsage($source)) {
$source->delete();
}
return $file;
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.