Problem/Motivation

Currently the majority of the Entity API methods (especially id()) do not strongly indicate their return type and in many cases allow a wider return type than is ever utilized.

We should strength the return type.

This is also required for eventual PHPStan L9 coverage

Steps to reproduce

Proposed resolution

Remaining tasks

#3224376: UserInterface::id(), AccountInterface::id() should return int to match typehints

User interface changes

N/A

API changes

See child issues

Data model changes

See child issues

Release notes snippet

See child issues

Comments

cmlara created an issue. See original summary.

jurgenhaas’s picture

Adding a related issue where the status field value is an integer in the content entity while the same value in the original is a string.

cmlara’s picture

Opened #3441689: [META] Stronger Typing for Entity API. The scope is wider than just the Entity subsystem, however it is the root cause of some entity issues. It wont solve existing issues, however it will set a standard for going forward.

Version: 11.x-dev » main

Drupal core is now using the main branch as the primary development branch. New developments and disruptive changes should now be targeted to the main branch.

Read more in the announcement.

casey’s picture

donquixote’s picture

I can see two scenarios here:

  • For existing entity classes and interfaces, we cannot narrow the declared return type of id(), as this would break BC for subclasses in contrib.
    We can cast the value.
  • For new entity types, or for existing types in Drupal 12, we can cast the value _and_ narrow the declared return type to "?int".

To make this possible, we could introduce two traits:

  • SoftIntegerIdEntityTrait, which casts the id value but does not narrow the declared return type.
    This would be used for most existing entity classes in Drupal core.
    • IntegerIdEntityTrait, which casts the id value but does not narrow the declared return type.
      This could be used by new entity classes introduced in core or contrib, or for existing entity classes in new major versions of core or contrib.
    • Another interesting place for this conversion could be in the respective TypedData classes, or in class IntegerItem, which I think are responsible for reading and processing those values. But these classes have always been a mystery to me :)

amateescu’s picture