Skip to content

Allow null $data in form factory stubs - #529

Merged
ondrejmirtes merged 1 commit into
2.1.xfrom
form-data-nullable
Nov 29, 2026
Merged

ondrejmirtes merged 1 commit into
2.1.xfrom
form-data-nullable

Conversation

@ondrejmirtes

Copy link
Copy Markdown
Member

FormFactoryInterface::create(), createNamed(), createBuilder(), createNamedBuilder() and AbstractController::createForm() default $data to null and already return FormInterface<null|TData> / FormBuilderInterface<null|TData> for it, but declared @param TData $data.

So create(DataClassType::class) or create(DataClassType::class, null) inferred TData = DataClass|null. With phpstan/phpstan-src#7251, which checks inferred template types against bounds that mention other templates (bleeding edge), that gives a false positive on valid code:

Type DataClassType inferred for template type TFormType in call to method FormFactoryInterface::create() is not within its bound FormTypeInterface<DataClass|null>.

This changes $data to TData|null. Inferred types don't change: create(DataClassType::class) is still FormInterface<DataClass|null>, and passing a DataClass still gives FormInterface<DataClass>. I added a test for an explicit null.

Checked with phpstan-src#7251 and bleeding edge on tests/Type/Symfony/data/form_data_type.php: the old stubs report 5 of these errors, the new ones report none. Passing data of the wrong type (create(DataClassType::class, new stdClass())) is still reported.

The form factory methods and AbstractController::createForm() default
$data to null and already return FormInterface<null|TData> for it, but
declared it as TData. Passing or omitting null therefore inferred
TData = DataClass|null, which a FormTypeInterface<DataClass> form type does
not satisfy, so PHPStan's check of inferred template types against their
bounds (bleeding edge, phpstan/phpstan-src#7251) reported valid calls.

Amp-Thread-ID: https://ampcode.com/threads/T-01a22307-fb39-7133-a55b-a5cc3cda81e7
@ondrejmirtes
ondrejmirtes merged commit 21e0684 into 2.1.x Nov 29, 2026
51 checks passed
@ondrejmirtes
ondrejmirtes deleted the form-data-nullable branch November 29, 2026 15:28
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.

1 participant