function FileExampleFileHelper::getManagedFile

Utility function to check for and return a managed file.

In this demonstration code we don't necessarily know if a file is managed or not, so often need to check to do the correct behavior. Normal code would not have to do this, as it would be working with either managed or unmanaged files.

Parameters

string $uri: The URI of the file, like public://test.txt.

Return value

\Drupal\file\FileInterface|bool A file object that matches the URI, or FALSE if not a managed file.

File

modules/file_example/src/FileExampleFileHelper.php, line 49

Class

FileExampleFileHelper
A file helper class for file_example.

Namespace

Drupal\file_example

Code

public function getManagedFile($uri) {
    // We'll use an entity query to get the managed part of the file.
    $file_storage = $this->entityTypeManager
        ->getStorage('file');
    $query = $file_storage->getQuery()
        ->accessCheck(FALSE)
        ->condition('uri', $uri);
    $fid = $query->execute();
    if (!empty($fid)) {
        
        /** @var \Drupal\file\Entity\File $file */
        $file = $file_storage->load(reset($fid));
        return $file;
    }
    // Return FALSE because there's no managed file for that URI.
    return FALSE;
}