You are here

public function FileRepository::copy in Drupal 10

File

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

Class

FileRepository
Provides a file entity repository.

Namespace

Drupal\file

Code

public function copy(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
    ->copy($source
    ->getFileUri(), $destination, $replace);

  // If we are replacing an existing file, load it.
  if ($replace === FileSystemInterface::EXISTS_REPLACE && ($existing = $this
    ->loadByUri($uri))) {
    $file = $existing;
  }
  else {
    $file = $source
      ->createDuplicate();
    $file
      ->setFileUri($uri);

    // If we are renaming around an existing file (rather than a directory),
    // use its basename for the filename.
    if ($replace === FileSystemInterface::EXISTS_RENAME && is_file($destination)) {
      $file
        ->setFilename($this->fileSystem
        ->basename($destination));
    }
    else {
      $file
        ->setFilename($this->fileSystem
        ->basename($uri));
    }
  }
  $file
    ->save();

  // Inform modules that the file has been copied.
  $this->moduleHandler
    ->invokeAll('file_copy', [
    $file,
    $source,
  ]);
  return $file;
}