Skip to content

Fix phpstan/phpstan#14250: trait.duplicateMethod is not reported#5181

Open
phpstan-bot wants to merge 1 commit intophpstan:2.1.xfrom
phpstan-bot:create-pull-request/patch-y7tlrzi
Open

Fix phpstan/phpstan#14250: trait.duplicateMethod is not reported#5181
phpstan-bot wants to merge 1 commit intophpstan:2.1.xfrom
phpstan-bot:create-pull-request/patch-y7tlrzi

Conversation

@phpstan-bot
Copy link
Collaborator

Summary

Duplicate method declarations within traits were not being reported with the trait.duplicateMethod identifier. The existing DuplicateDeclarationRule listens for InClassNode, but InClassNode is never emitted for trait declarations — NodeScopeResolver skips trait nodes entirely at declaration time (they are only processed when used by a class).

Changes

  • Created src/Rules/Classes/DuplicateTraitDeclarationRule.php — a new rule that implements Rule<InTraitNode> and checks for duplicate methods, properties, and constants within trait declarations
  • The rule mirrors the logic of DuplicateDeclarationRule but operates on InTraitNode (emitted when a trait is used by a class)
  • Registered at level 0 via #[RegisteredRule(level: 0)], same as the original rule
  • Added test class tests/PHPStan/Rules/Classes/DuplicateTraitDeclarationRuleTest.php
  • Added test data tests/PHPStan/Rules/Classes/data/bug-14250.php

Root cause

NodeScopeResolver::processStmtNodes() short-circuits trait declarations (line 967-968), returning immediately without emitting InClassNode. This is by design — traits are processed in the context of their using class via processTraitUse(). However, InTraitNode IS emitted during trait use processing, so a rule listening for InTraitNode can detect duplicate declarations within traits. No such rule existed before this fix.

Test

The regression test in bug-14250.php defines a trait with two methods named doSomething() and a class that uses the trait. The test expects one error: "Cannot redeclare method Bug14250\MyTrait::doSomething()." at line 11.

Fixes phpstan/phpstan#14250

… methods in traits

- Created DuplicateTraitDeclarationRule that listens for InTraitNode to detect duplicate methods, properties, and constants within trait declarations
- The existing DuplicateDeclarationRule only handles InClassNode, which is never emitted for traits (NodeScopeResolver skips trait declarations at line 967-968)
- InTraitNode is emitted when a trait is used by a class, allowing the new rule to check trait bodies for duplicates
- Added regression test in tests/PHPStan/Rules/Classes/data/bug-14250.php
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