You are here

function file_move in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/file/file.module \file_move()
  2. 4 includes/file.inc \file_move()
  3. 5 includes/file.inc \file_move()
  4. 6 includes/file.inc \file_move()
  5. 7 includes/file.inc \file_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:

Return value

\Drupal\file\FileInterface|false Resulting file entity for success, or FALSE in the event of an error.

See also

\Drupal\Core\File\FileSystemInterface::move()

hook_file_move()

12 calls to file_move()
FileMoveTest::testNormal in core/modules/image/tests/src/Functional/FileMoveTest.php
Tests moving a randomly generated image.
FileUploadForm::createMediaFromValue in core/modules/media_library/src/Form/FileUploadForm.php
Creates a new, unsaved media item from a source field value.
ImageItem::generateSampleValue in core/modules/image/src/Plugin/Field/FieldType/ImageItem.php
Generates placeholder field values.
image_field_config_update in core/modules/image/image.module
Implements hook_ENTITY_TYPE_update() for 'field_config'.
image_field_storage_config_update in core/modules/image/image.module
Implements hook_ENTITY_TYPE_update() for 'field_storage_config'.

... See full list

File

core/modules/file/file.module, line 200
Defines a "managed_file" Form API field and a "file" field for Field module.

Code

function file_move(FileInterface $source, $destination = NULL, $replace = FileSystemInterface::EXISTS_RENAME) {

  /** @var \Drupal\Core\File\FileSystemInterface $file_system */
  $file_system = \Drupal::service('file_system');

  /** @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager */
  $stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
  if (!$stream_wrapper_manager
    ->isValidUri($destination)) {
    if (($realpath = $file_system
      ->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.', [
        '%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.', [
        '%file' => $source
          ->getFileUri(),
        '%destination' => $destination,
      ]);
    }
    \Drupal::messenger()
      ->addError(t('The specified file %file could not be moved because the destination is invalid. More information is available in the system log.', [
      '%file' => $source
        ->getFileUri(),
    ]));
    return FALSE;
  }
  try {
    $uri = $file_system
      ->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) {
      $existing_files = \Drupal::entityTypeManager()
        ->getStorage('file')
        ->loadByProperties([
        'uri' => $uri,
      ]);
      if (count($existing_files)) {
        $existing = reset($existing_files);
        $delete_source = TRUE;
        $file->fid = $existing
          ->id();
        $file->uuid = $existing
          ->uuid();
      }
    }
    elseif ($replace == FileSystemInterface::EXISTS_RENAME && is_file($destination)) {
      $file
        ->setFilename(\Drupal::service('file_system')
        ->basename($destination));
    }
    $file
      ->save();

    // Inform modules that the file has been moved.
    \Drupal::moduleHandler()
      ->invokeAll('file_move', [
      $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;
  } catch (FileException $e) {
    return FALSE;
  }
}