Skip to content

Commit

Permalink
Do not analyse trait method that's shadowed in the using class
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed May 15, 2020
1 parent 79efcd7 commit a2044e6
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 2 deletions.
19 changes: 19 additions & 0 deletions src/Analyser/NodeScopeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
use PHPStan\Reflection\ParametersAcceptorSelector;
use PHPStan\Reflection\PassedByReference;
use PHPStan\Reflection\Php\DummyParameter;
use PHPStan\Reflection\Php\PhpMethodReflection;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Type\Accessory\NonEmptyArrayType;
use PHPStan\Type\ArrayType;
Expand Down Expand Up @@ -315,6 +316,24 @@ private function processStmtNode(
$scope = $this->processStmtVarAnnotation($scope, $stmt, $stmt->expr);
}

if ($stmt instanceof Node\Stmt\ClassMethod) {
if (!$scope->isInClass()) {
throw new \PHPStan\ShouldNotHappenException();
}
if (
$scope->isInTrait()
&& $scope->getClassReflection()->hasNativeMethod($stmt->name->toString())
) {
$methodReflection = $scope->getClassReflection()->getNativeMethod($stmt->name->toString());
if ($methodReflection instanceof PhpMethodReflection) {
$declaringTrait = $methodReflection->getDeclaringTrait();
if ($declaringTrait === null || $declaringTrait->getName() !== $scope->getTraitReflection()->getName()) {
return new StatementResult($scope, false, false, []);
}
}
}
}

$nodeCallback($stmt, $scope);

if ($stmt instanceof Node\Stmt\Declare_) {
Expand Down
4 changes: 2 additions & 2 deletions tests/PHPStan/Analyser/data/get-parent-class.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class Bar extends Foo

use FooTrait;

public function doFoo()
public function doBar()
{
'inChildClass';
}
Expand All @@ -31,7 +31,7 @@ function (string $s) {
trait FooTrait
{

public function doFoo()
public function doBaz()
{
'inTrait';
}
Expand Down
8 changes: 8 additions & 0 deletions tests/PHPStan/Rules/Methods/CallMethodsRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1321,4 +1321,12 @@ public function testMergeInheritedPhpDocs(): void
]);
}

public function testShadowedTraitMethod(): void
{
$this->checkThisOnly = false;
$this->checkNullables = true;
$this->checkUnionTypes = true;
$this->analyse([__DIR__ . '/data/shadowed-trait-method.php'], []);
}

}
25 changes: 25 additions & 0 deletions tests/PHPStan/Rules/Methods/data/shadowed-trait-method.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace ShadowedTraitMethod;

trait FooTrait
{

public function doFoo()
{
$this->doBar();
}

}

class Foo
{

use FooTrait;

public function doFoo()
{

}

}

0 comments on commit a2044e6

Please sign in to comment.