Inconsistency between ByteSizeMarkup::create and File::getSize

Created on 16 January 2024, 8 months ago

Problem/Motivation

The File module uses File::getSize to fetch the size of a file entity. The API docs for this function say it returns the size of the file in bytes, or NULL if not determined. https://api.drupal.org/api/drupal/core%21modules%21file%21src%21Entity%2...

In Drupal 10.2, the old format_size PHP function has been deprecated and is being transitioned to ByteSizeMarkup::create. I can't find API docs for this method, but the codebase shows that it takes a float or int as the filesize. https://git.drupalcode.org/project/drupal/-/blob/10.2.x/core/lib/Drupal/...

See change record: https://www.drupal.org/node/2999981

This poses a problem because in a lot of cases I'm seeing File::getSize piped straight into ByteSizeMarkup::create, assuming that the former returns a value. In some cases where File::getSize returns a NULL, and it can, PHP will immediately throw a TypeError on running ByteSizeMarkup::create with the NULL filesize as the first argument.

Here's an example of where it bit me: https://git.drupalcode.org/project/drupal/-/blob/11.x/core/modules/file/...

Steps to reproduce

  1. Create a file entity with null filesize (eg. remote or otherwise)
  2. Go to /admin/content/media

This should immediately crash with a TypeError.

Proposed resolution

Identify all cases of code like ByteSizeMarkup::create($file->getSize()) and transform them to ByteSizeMarkup::create($file->getSize() ?? 0) if we cannot be sure that $file->getSize() will return a value.

Alternatively, change File::getSize so it can only return an int. Or perhaps let ByteSizeMarkup::create take a 0 as the default for the first argument.

In my case I've gone with the first approach in a patch of my own (that I'll contribute back), but this might not catch everything, and won't help with similar issues in contrib modules or custom code.

Merge request link

Not yet.

Remaining tasks

Decide on fix and implement.

User interface changes

None.

API changes

To be determined.

Data model changes

None.

Release notes snippet

To be determined.

🐛 Bug report
Status

Active

Version

10.2

Component
File system 

Last updated 1 day ago

Created by

🇦🇺Australia geoffreyr

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024