Skip to content

Commit 4f8d0b3

Browse files
phpstan-botclaude
andcommitted
Still report method_exists($this) as always true when method is defined in the trait
When a trait defines a method itself, method_exists($this, 'method') will always be true regardless of which class uses the trait. Only suppress the report when the method is NOT defined in the trait, since then the result depends on the using class. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent b18a0b0 commit 4f8d0b3

2 files changed

Lines changed: 14 additions & 1 deletion

File tree

src/Rules/Comparison/ImpossibleCheckTypeHelper.php

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,16 @@ public function findSpecifiedType(
200200
$objectArg = $args[0]->value;
201201

202202
if ($scope->isInTrait() && ExpressionDependsOnThisHelper::isExpressionDependentOnThis($objectArg)) {
203-
return null;
203+
$traitReflection = $scope->getTraitReflection();
204+
$methodArgValue = $args[1]->value;
205+
$methodArgType = $this->treatPhpDocTypesAsCertain ? $scope->getType($methodArgValue) : $scope->getNativeType($methodArgValue);
206+
$constantMethodNames = $methodArgType->getConstantStrings();
207+
if (
208+
count($constantMethodNames) !== 1
209+
|| !$traitReflection->hasNativeMethod($constantMethodNames[0]->getValue())
210+
) {
211+
return null;
212+
}
204213
}
205214
$objectType = $this->treatPhpDocTypesAsCertain ? $scope->getType($objectArg) : $scope->getNativeType($objectArg);
206215

tests/PHPStan/Rules/Comparison/ImpossibleCheckTypeFunctionCallRuleTest.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,10 @@ public function testImpossibleCheckTypeFunctionCall(): void
183183
'Call to function method_exists() with CheckTypeFunctionCall\MethodExists and \'testWithNewObjectIn…\' will always evaluate to true.',
184184
635,
185185
],
186+
[
187+
'Call to function method_exists() with $this(CheckTypeFunctionCall\MethodExistsWithTrait) and \'method\' will always evaluate to true.',
188+
650,
189+
],
186190
[
187191
'Call to function method_exists() with \'CheckTypeFunctionCall\\\\MethodExistsWithTrait\' and \'method\' will always evaluate to true.',
188192
659,

0 commit comments

Comments
 (0)