file_move(FileInterface $source,$destination= NULL, $replace = FILE_EXISTS_RENAME)
Moves a file to a new location and update the file's database entry.
\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:
\Drupal\file\FileInterface|false Resulting file entity for success, or FALSE in the event of an error.
function file_move(FileInterface $source, $destination = NULL, $replace = FILE_EXISTS_RENAME) { if (!file_valid_uri($destination)) { if (($realpath = drupal_realpath($source->getFileUri())) !== FALSE) { \Drupal::logger('file')->notice('File %file (%realpath) could not be moved because the destination %destination is invalid. This may be caused by improper use of file_move() or a missing stream wrapper.', array('%file' => $source->getFileUri(), '%realpath' => $realpath, '%destination' => $destination)); } else { \Drupal::logger('file')->notice('File %file could not be moved because the destination %destination is invalid. This may be caused by improper use of file_move() or a missing stream wrapper.', array('%file' => $source->getFileUri(), '%destination' => $destination)); } drupal_set_message(t('The specified file %file could not be moved because the destination is invalid. More information is available in the system log.', array('%file' => $source->getFileUri())), 'error'); return FALSE; } if ($uri = file_unmanaged_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 == FILE_EXISTS_REPLACE) { $existing_files = entity_load_multiple_by_properties('file', array('uri' => $uri)); if (count($existing_files)) { $existing = reset($existing_files); $delete_source = TRUE; $file->fid = $existing->id(); $file->uuid = $existing->uuid(); } } // If we are renaming around an existing file (rather than a directory), // use its basename for the filename. elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) { $file->setFilename(drupal_basename($destination)); } $file->save(); // Inform modules that the file has been moved. \Drupal::moduleHandler()->invokeAll('file_move', array($file, $source)); // Delete the original if it's not in use elsewhere. if ($delete_source && !\Drupal::service('file.usage')->listUsage($source)) { $source->delete(); } return $file; } return FALSE; }
© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!modules!file!file.module/function/file_move/8.1.x