Skip to content

Commit

Permalink
identicalClassComparison: fix callable false positive (#81)
Browse files Browse the repository at this point in the history
  • Loading branch information
janedbal committed Feb 3, 2023
1 parent 24142f7 commit 14691a8
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 13 deletions.
17 changes: 10 additions & 7 deletions src/Rule/ForbidIdenticalClassComparisonRule.php
Expand Up @@ -11,6 +11,7 @@
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Rules\Rule;
use PHPStan\Type\CallableType;
use PHPStan\Type\Constant\ConstantBooleanType;
use PHPStan\Type\MixedType;
use PHPStan\Type\ObjectType;
Expand All @@ -25,6 +26,11 @@ class ForbidIdenticalClassComparisonRule implements Rule
{

private const DEFAULT_BLACKLIST = [DateTimeInterface::class];
private const IGNORED_TYPES = [
MixedType::class, // mixed is "maybe" accepted by any (denied) class
ObjectWithoutClassType::class, // object is "maybe" accepted by any (denied) class
CallableType::class, // any non-final class descendant can have __invoke method causing it to be "maybe" accepted by any (denied) class
];

/**
* @var array<int, class-string<object>>
Expand Down Expand Up @@ -75,13 +81,10 @@ public function processNode(Node $node, Scope $scope): array
return []; // always-true or always-false, already reported by native PHPStan (like $a === $a)
}

if (
$leftType instanceof MixedType
|| $leftType instanceof ObjectWithoutClassType
|| $rightType instanceof MixedType
|| $rightType instanceof ObjectWithoutClassType
) {
return []; // those may contain forbidden class, but that is too strict
foreach (self::IGNORED_TYPES as $ignoredType) {
if ($leftType instanceof $ignoredType || $rightType instanceof $ignoredType) {
return [];
}
}

$errors = [];
Expand Down
14 changes: 8 additions & 6 deletions tests/Rule/data/ForbidIdenticalClassComparisonRule/code.php
Expand Up @@ -23,14 +23,16 @@ public function testNonObject(?DateTimeImmutable $a, string $b): void
}
}

public function testMixed(DateTimeImmutable $a, mixed $b): void
{
$a === $b;
}

public function testAnyObject(DateTimeImmutable $a, object $b): void
public function testProblematicTypes(
DateTimeImmutable $a,
mixed $b,
object $c,
callable $d
): void
{
$a === $b;
$a === $c;
$a === $d;
}

public function testRegular(DateTimeImmutable $a, DateTimeImmutable $b): void
Expand Down

0 comments on commit 14691a8

Please sign in to comment.