FileRepository::loadByUri does not returns the most recent file if several files match the URI

Created on 31 March 2022, over 3 years ago
Updated 4 February 2023, over 2 years ago

Problem/Motivation

The method \Drupal\file\FileRepository::loadByUri use the \Drupal\Core\Entity\EntityHandlerBase::loadByProperties to load the files by uri property. When multiple files match to the uri the code loop throught the $files to break the loop and returns the first match, the problem is with the usage of the method loadByProperties, the results are sorted by chronological order.

Steps to reproduce

Run the code $files = \Drupal::entityTypeManager()->getStorage('file')->loadByProperties(); and checks the array keys (which are files IDs), they are in chronological order.

Proposed resolution

Use the entity query instead the loadByProperty method as following code :

    $fids = $fileStorage
      ->getQuery()
      ->condition('uri', $uri)
      ->accessCheck(FALSE)
      ->sort('fid', 'DESC')
      ->execute();
    /** @var \Drupal\file\FileInterface[] $files */
    $files = $fileStorage->loadMultiple($fids);
🐛 Bug report
Status

Needs work

Version

10.1

Component
File system 

Last updated 5 days ago

Created by

🇫🇷France xavier.masson Haute-Normandie

Live updates comments and jobs are added and updated live.
  • Needs tests

    The change is currently missing an automated test that fails when run with the original code, and succeeds when the bug has been fixed.

Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • 🇺🇸United States smustgrave

    This issue is being reviewed by the kind folks in Slack, #needs-review-queue-initiative. We are working to keep the size of Needs Review queue [2700+ issues] to around 400 (1 month or less), following Review a patch or merge request as a guide.

    Thank you for reporting

    This will require a test case to show the issue.

  • 🇮🇳India mohit_aghera Rajkot

    I came across this issue while doing bugsmash triage.

    I'm somewhat confused about the title

    FileRepository::loadByUri does not returns the most recent file if several files match the URI

    Since URI is unique value, I'm wondering how we can end-up with incorrect value.

    i.e. the following snippet already does the exact validation of $uri and returns the value.

    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;
            }
          }
Production build 0.71.5 2024