function FileRepository::copy

Same name in other branches
  1. 10 core/modules/file/src/FileRepository.php \Drupal\file\FileRepository::copy()
  2. 11.x core/modules/file/src/FileRepository.php \Drupal\file\FileRepository::copy()

Overrides FileRepositoryInterface::copy

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("Invalid stream wrapper: {$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;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.