Skip to content

Commit

Permalink
Fix comparison with get_class() in traits always evaluate to true
Browse files Browse the repository at this point in the history
  • Loading branch information
staabm committed Dec 4, 2022
1 parent 66dc2ad commit f376d3d
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/Type/Php/GetClassDynamicReturnTypeExtension.php
Expand Up @@ -17,6 +17,7 @@
use PHPStan\Type\ObjectType;
use PHPStan\Type\ObjectWithoutClassType;
use PHPStan\Type\StaticType;
use PHPStan\Type\StringType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeTraverser;
use PHPStan\Type\TypeWithClassName;
Expand All @@ -34,6 +35,7 @@ public function isFunctionSupported(FunctionReflection $functionReflection): boo
public function getTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $functionCall, Scope $scope): Type
{
$args = $functionCall->getArgs();

if (count($args) === 0) {
if ($scope->isInClass()) {
return new ConstantStringType($scope->getClassReflection()->getName(), true);
Expand All @@ -42,6 +44,10 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
return new ConstantBooleanType(false);
}

if ($scope->isInTrait()) {
return new StringType();
}

$argType = $scope->getType($args[0]->value);

return TypeTraverser::map(
Expand Down
Expand Up @@ -613,4 +613,10 @@ public function testPhpUnitIntegration(): void
$this->analyse([__DIR__ . '/../../Analyser/data/phpunit-integration.php'], []);
}

public function testBug3633(): void
{
$this->checkAlwaysTrueStrictComparison = true;
$this->analyse([__DIR__ . '/data/bug-3633.php'], []);
}

}
30 changes: 30 additions & 0 deletions tests/PHPStan/Rules/Comparison/data/bug-3633.php
@@ -0,0 +1,30 @@
<?php declare(strict_types = 1);

namespace Bug3633;

trait Foo {
public function test(): void {
if (get_class($this) === HelloWorld::class) {
echo "OK";
}
if (get_class($this) === OtherClass::class) {
echo "OK";
}
}
}

class HelloWorld {
use Foo;

public function bar(): void {
$this->test();
}
}

class OtherClass {
use Foo;

public function bar(): void {
$this->test();
}
}

0 comments on commit f376d3d

Please sign in to comment.