Skip to content

Keep nullable types of a generic closure return type when the accepting callable is nullable - #7301

Open
odolbeau wants to merge 2 commits into
phpstan:2.3.xfrom
odolbeau:fix/nullable-callable-generic-return-type
Open

odolbeau wants to merge 2 commits into
phpstan:2.3.xfrom
odolbeau:fix/nullable-callable-generic-return-type

Conversation

@odolbeau

@odolbeau odolbeau commented Dec 3, 2026

Copy link
Copy Markdown

Follow-up to #6392 (93eaf56).

Below level 8, a closure passed to a nullable callable parameter still gets the nullable types inside its generic return type removed, so an invariant template no longer matches:

/** @template T */
final class Box
{
	/** @param T $value */
	public function __construct(public mixed $value) {}

	/**
	 * @template TReturn
	 * @param (callable($this): TReturn)|null $callback
	 * @return TReturn|null
	 */
	public function pipe(?callable $callback): mixed
	{
		return $callback === null ? null : $callback($this);
	}
}

/** @param array{id: int, name: string|null} $item */
function test(array $item): void
{
	(new Box($item))->pipe(fn (Box $box): Box => $box);
}
Parameter #1 $callback of method Box<array<string, int|string|null>>::pipe() expects (callable(Box<array{id: int, name: string|null}>): Box<array{id: int, name: string|null}>)|null, Closure(Box): Box<array{id: int, name: string|null}> given.

No error on level 8, nor without |null on the parameter. In practice it hits Laravel's Conditionable::when()/unless() on collections of shapes with a nullable value (Larastan declares TValue invariant).

RuleLevelHelper::transformAcceptedType() only reads the accepting return type when the accepting type is a ParametersAcceptor. (callable(): X)|null is a union, so the return type was null and the old null-stripping mapping applied. The accepting type is now stripped of null before reading its return type, in the PHP class and its turbo-ext twin.

odolbeau and others added 2 commits December 3, 2026 11:46
…ng callable is nullable

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@staabm

staabm commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

please create a issue describing your use-case and providing a phpstan.org/try reproducer

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