function FileRepository::createOrUpdate

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

Create a file entity or update if it exists.

Parameters

string $uri: The file URI.

string $destination: The destination URI.

bool $rename: Whether to rename the file.

Return value

\Drupal\file\Entity\File|\Drupal\file\FileInterface The file entity.

Throws

\Drupal\Core\Entity\EntityStorageException Thrown when there is an error saving the file.

1 call to FileRepository::createOrUpdate()
FileRepository::writeData in core/modules/file/src/FileRepository.php
Writes a file to the specified destination and creates a file entity.

File

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

Class

FileRepository
Provides a file entity repository.

Namespace

Drupal\file

Code

protected function createOrUpdate(string $uri, string $destination, bool $rename) : FileInterface {
    $file = $this->loadByUri($uri);
    if ($file === NULL) {
        $file = File::create([
            'uri' => $uri,
        ]);
        $file->setOwnerId($this->currentUser
            ->id());
    }
    if ($rename && is_file($destination)) {
        $file->setFilename($this->fileSystem
            ->basename($destination));
    }
    $file->setPermanent();
    $file->save();
    return $file;
}

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