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

Created on 31 March 2022, over 2 years ago
Updated 4 February 2023, over 1 year 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 1 day 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.

Production build 0.71.5 2024