You are here

public function File::createOrReuseFromUri in Helper 8

Creates or reuses a file object based on a URI.

Parameters

string $uri: A string containing the URI.

bool $reuse_existing: If TRUE will try to reuse an existing file with the same URI. If FALSE will always create a new file.

Return value

\Drupal\file\FileInterface A file object.

File

src/File.php, line 54

Class

File
Provides helpers for working with files.

Namespace

Drupal\helper

Code

public function createOrReuseFromUri($uri, $reuse_existing = TRUE) {
  if ($reuse_existing) {

    // Check if this file already exists, and if so, return that.
    $files = $this->fileStorage
      ->loadByProperties([
      'uri' => $uri,
    ]);
    if ($valid_files = array_filter($files, [
      $this,
      'filterValidFiles',
    ])) {
      return reset($valid_files);
    }
  }

  // If an existing file could not be found, create a new file.
  return $this->fileStorage
    ->create([
    'uri' => $uri,
    'uid' => \Drupal::currentUser()
      ->id(),
  ]);
}