Skip to content

PHPStan: infer targetEntity from property type for ManyToOne associations#38

Merged
JanTvrdik merged 2 commits intomasterfrom
fix/phpstan-manytoone-type-inference
Dec 15, 2025
Merged

PHPStan: infer targetEntity from property type for ManyToOne associations#38
JanTvrdik merged 2 commits intomasterfrom
fix/phpstan-manytoone-type-inference

Conversation

@JanTvrdik
Copy link
Member

Summary

  • Extends PHPStan type inference to work for ManyToOne associations without explicit targetEntity attribute
  • Previously only OneToOne associations could infer target entity from property type
  • Adds test entities and test cases to verify the fix (reproduces issue PHPStan rules not working correctly? #37)

Problem

When using associations without explicit targetEntity attribute:

#[ManyToOne(inversedBy: 'subordinates')]
public ?Employee $supervisor = null;

PHPStan would incorrectly report: "Property 'Employee::$supervisor' is not a valid Doctrine association."

Solution

Extended the getAssociationTargetTypeFromPropertyReflection method to also infer target entity from property type for ManyToOne associations, not just OneToOne.

Test plan

  • Added Employee and EmployeeSettings test entities replicating issue PHPStan rules not working correctly? #37
  • Added test cases for associations without explicit targetEntity
  • All PHPStan integration tests pass (both with and without phpstan-doctrine)
  • All unit tests pass
  • PHPStan analysis passes
  • Code style checks pass

Fixes #37

…ions

Previously, when using associations without explicit targetEntity attribute,
PHPStan would only infer the target entity from the property type for
OneToOne associations. This left ManyToOne associations without targetEntity
attribute incorrectly reported as "not a valid Doctrine association".

This change extends type inference to also work for ManyToOne associations,
matching the behavior users expect when not using phpstan-doctrine.

Fixes #37
@JanTvrdik JanTvrdik force-pushed the fix/phpstan-manytoone-type-inference branch from dbf9e23 to f744d0e Compare December 15, 2025 14:57
@JanTvrdik JanTvrdik requested a review from janedbal December 15, 2025 15:49
@janedbal
Copy link
Member

Or, we might drop this fallback completely to mitigate all maintenance. And only support PHPStan inference when phpstan-doctrine is used properly.

@JanTvrdik JanTvrdik merged commit 0eae48b into master Dec 15, 2025
21 checks passed
@JanTvrdik JanTvrdik deleted the fix/phpstan-manytoone-type-inference branch December 15, 2025 16:20
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.

PHPStan rules not working correctly?

2 participants

Comments