Skip to content

Commit 07c6a0d

Browse files
committed
Improve loose comparison on array type
1 parent 5a94e38 commit 07c6a0d

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

src/Type/Accessory/NonEmptyArrayType.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
use PHPStan\Type\AcceptsResult;
1010
use PHPStan\Type\BooleanType;
1111
use PHPStan\Type\CompoundType;
12+
use PHPStan\Type\Constant\ConstantBooleanType;
1213
use PHPStan\Type\Constant\ConstantFloatType;
1314
use PHPStan\Type\Constant\ConstantIntegerType;
1415
use PHPStan\Type\ErrorType;
@@ -402,6 +403,10 @@ public function isScalar(): TrinaryLogic
402403

403404
public function looseCompare(Type $type, PhpVersion $phpVersion): BooleanType
404405
{
406+
if ($type->isArray()->yes() && $type->isIterableAtLeastOnce()->no()) {
407+
return new ConstantBooleanType(false);
408+
}
409+
405410
return new BooleanType();
406411
}
407412

src/Type/ArrayType.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,10 @@ public function isConstantValue(): TrinaryLogic
249249

250250
public function looseCompare(Type $type, PhpVersion $phpVersion): BooleanType
251251
{
252+
if ($type->isInteger()->yes()) {
253+
return new ConstantBooleanType(false);
254+
}
255+
252256
return new BooleanType();
253257
}
254258

tests/PHPStan/Analyser/nsrt/loose-comparisons.php

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -701,11 +701,19 @@ public function sayConstUnion(
701701
/**
702702
* @param uppercase-string $upper
703703
* @param lowercase-string $lower
704+
* @param array{} $emptyArr
705+
* @param non-empty-array $nonEmptyArr
706+
* @param int<10, 20> $intRange
704707
*/
705708
public function sayIntersection(
706709
string $upper,
707710
string $lower,
708711
string $s,
712+
array $emptyArr,
713+
array $nonEmptyArr,
714+
array $arr,
715+
int $i,
716+
int $intRange,
709717
): void
710718
{
711719
assertType('bool', '' == $upper);
@@ -731,7 +739,15 @@ public function sayIntersection(
731739
assertType('bool', strtoupper($s) == $lower); // should be false
732740
assertType('bool', strtolower($s) == $lower);
733741
assertType('bool', $lower == $upper); // should be false
734-
}
735742

743+
assertType('false', $arr == $i);
744+
assertType('false', $nonEmptyArr == $i);
745+
assertType('false', $arr == $intRange);
746+
assertType('false', $nonEmptyArr == $intRange);
747+
assertType('bool', $emptyArr == $nonEmptyArr); // should be false
748+
assertType('false', $nonEmptyArr == $emptyArr);
749+
assertType('bool', $arr == $nonEmptyArr);
750+
assertType('bool', $nonEmptyArr == $arr);
751+
}
736752

737753
}

0 commit comments

Comments
 (0)