You are here

public function FileRepository::move in Drupal 10

File

core/modules/file/src/FileRepository.php, line 167

Class

FileRepository
Provides a file entity repository.

Namespace

Drupal\file

Code

public function move(FileInterface $source, string $destination, int $replace = FileSystemInterface::EXISTS_RENAME) : FileInterface {
  if (!$this->streamWrapperManager
    ->isValidUri($destination)) {
    throw new InvalidStreamWrapperException(sprintf('Invalid stream wrapper: %destination', [
      '%destination' => $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;
}