Fix type hints in FileInterface to align with reality

Created on 3 February 2022, over 2 years ago
Updated 20 March 2023, over 1 year ago

Problem/Motivation

\Drupal\file\Entity\File doesn't honor some type hints in \Drupal\file\FileInterface e.g the file size could be null because "the file itself might not exist or be available right now" but getSize() is supposed to return a string. Meanwhile setSize() accepts an integer, so the type for getSize() changes between string and integer depending on if you're getting from the database or from an entity object that is being built/modified. Likewise, the MIME type could be null if the MIME type guesser was unable to find a MIME type.

Steps to reproduce

You can create a file programmatically to play around with its methods:

$file = \Drupal\file\Entity\File::create(['created' => NULL]);
$file->getCreatedTime();
$file->getFileUri();
$file->setFileUri('lol');
$file->save();
$file = \Drupal\file\Entity\File::load($file->id());

Proposed resolution

Fix \Drupal\file\FileInterface type hints to also accept or return null where null is accepted and saved to the database:

  • getCreatedTime()
  • getFilename()
  • setFilename()
  • getMimeType()
  • setMimeType()
  • getSize()
  • setSize()

Fix \Drupal\file\FileInterface type hint to allow returning null where null cannot be saved to the database, but may be the current value because it hasn't been saved yet:

  • getFileUri()

Fix \Drupal\file\Entity\File method to ensure it returns an integer (or null) rather than a string, which is already documented to return an integer:

  • getCreatedTime()

Fix \Drupal\file\Entity\File method to ensure it returns an integer (or null) rather than a string, which previously was documented to return a string, while its setter accepts integer:

  • getSize()

Remaining tasks

In a followup issue targeting a future major version, the phpdoc type hints could be "upgraded" to actual type declarations for function arguments and return types.

API changes

File::getCreatedTime() and File::getSize() now return an integer (or null) rather than a string, which is useful if you want to use them with PHP functions that expect integers (you will still have to check if they are null, however). FileInterface::getCreatedTime() was already documented to return an integer anyways.

Data model changes

None.

πŸ› Bug report
Status

Fixed

Version

10.1 ✨

Component
File systemΒ  β†’

Last updated 1 day ago

Created by

πŸ‡ΊπŸ‡ΈUnited States mfb San Francisco

Live updates comments and jobs are added and updated live.
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