function FileRepository::copy

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

File

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

Class

FileRepository
Provides a file entity repository.

Namespace

Drupal\file

Code

public function copy(FileInterface $source, string $destination, FileExists|int $fileExists = FileExists::Rename) : FileInterface {
    if (!$fileExists instanceof FileExists) {
        // @phpstan-ignore staticMethod.deprecated
        $fileExists = FileExists::fromLegacyInt($fileExists, __METHOD__);
    }
    if (!$this->streamWrapperManager
        ->isValidUri($destination)) {
        throw new InvalidStreamWrapperException("Invalid stream wrapper: {$destination}");
    }
    $uri = $this->fileSystem
        ->copy($source->getFileUri(), $destination, $fileExists);
    // If we are replacing an existing file, load it.
    if ($fileExists === FileExists::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 ($fileExists === FileExists::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.