Skip to content

Make FieldItemListPropertyReflection entity property nullable#950

Merged
mglaman merged 1 commit intomglaman:mainfrom
Niklan:entity-property-nullable
Mar 16, 2026
Merged

Make FieldItemListPropertyReflection entity property nullable#950
mglaman merged 1 commit intomglaman:mainfrom
Niklan:entity-property-nullable

Conversation

@Niklan
Copy link
Contributor

@Niklan Niklan commented Mar 16, 2026

Currently, code like:

public function getFoo(): ?Foo {
  return $this->get('foo')->entity;
}

will produce an error: return.unusedType — "never returns null so it can be removed from the return type".

This is not true, because Drupal has no entity reference integrity by default. It means even if the field is required and has a value, it doesn't mean that the referenced entity actually exists. For example: the foo field has a reference ID 123, but the entity with ID 123 is no longer available (removed or otherwise).

But this rule forces a fix like this one:

-public function getFoo(): ?Foo {
+public function getFoo(): Foo {
   return $this->get('foo')->entity;
 }

And when the referenced entity is actually missing, you will have a fatal error in production, because ->entity will return null.

Because of this, when you understand the issue, you have to ignore every other line with that magic property, which is also not a valid solution. The most appropriate options are:

public function getFoo(): ?Foo {
  $entity = $this->get('foo')->entity;
  \assert($entity instanceof Foo || $entity === null);
  return $entity;
}

or

public function getFoo(): Foo {
  $entity = $this->get('foo')->entity;
  if (!$entity instanceof Foo) {
    throw new \RuntimeException('Required reference is missing');
  }
  return $entity;
}

It depends on project requirements, environment (with entity integrity protection it is safe to force a specific return type with an exception if needed), or style. But the current behavior simply forces developers down a path which will introduce dangerous bugs.

@mglaman mglaman merged commit 81b3c38 into mglaman:main Mar 16, 2026
15 checks passed
@Niklan Niklan deleted the entity-property-nullable branch March 16, 2026 13:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants