function FileRepository::loadByUri

Same name and namespace in other branches
  1. 9 core/modules/file/src/FileRepository.php \Drupal\file\FileRepository::loadByUri()
  2. 11.x core/modules/file/src/FileRepository.php \Drupal\file\FileRepository::loadByUri()

Loads the first File entity found with the specified URI.

Parameters

string $uri: The file URI.

Return value

\Drupal\file\FileInterface|null The first file with the matched URI if found, NULL otherwise.

Overrides FileRepositoryInterface::loadByUri

3 calls to FileRepository::loadByUri()
FileRepository::copy in core/modules/file/src/FileRepository.php
Copies a file to a new location and adds a file record to the database.
FileRepository::createOrUpdate in core/modules/file/src/FileRepository.php
Create a file entity or update if it exists.
FileRepository::move in core/modules/file/src/FileRepository.php
Moves a file to a new location and update the file's database entry.

File

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

Class

FileRepository
Provides a file entity repository.

Namespace

Drupal\file

Code

public function loadByUri(string $uri) : ?FileInterface {
  $fileStorage = $this->entityTypeManager
    ->getStorage('file');
  /** @var \Drupal\file\FileInterface[] $files */
  $files = $fileStorage->loadByProperties([
    'uri' => $uri,
  ]);
  if (count($files)) {
    foreach ($files as $item) {
      // Since some database servers sometimes use a case-insensitive
      // comparison by default, double check that the filename is an exact
      // match.
      if ($item->getFileUri() === $uri) {
        return $item;
      }
    }
  }
  return NULL;
}

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