Skip to content

Commit

Permalink
Improve ArrayType::castToArrayKeyType() for booleans
Browse files Browse the repository at this point in the history
  • Loading branch information
jlherren authored and ondrejmirtes committed Mar 2, 2022
1 parent 265e181 commit 7ace968
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/Type/ArrayType.php
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,11 @@ public static function castToArrayKeyType(Type $offsetType): Type
return $offsetType;
}

if ($offsetType instanceof FloatType || $offsetType instanceof BooleanType || $offsetType->isNumericString()->yes()) {
if ($offsetType instanceof BooleanType) {
return new UnionType([new ConstantIntegerType(0), new ConstantIntegerType(1)]);
}

if ($offsetType instanceof FloatType || $offsetType->isNumericString()->yes()) {
return new IntegerType();
}

Expand Down
17 changes: 17 additions & 0 deletions tests/PHPStan/Analyser/data/constant-array-type-set.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,21 @@ public function doBar5(int $offset): void
assertType('non-empty-array<int<0, 4>, bool>', $a);
}

public function doBar6(bool $offset): void
{
$a = [false, false, false];
$a[$offset] = true;
assertType('array{bool, bool, false}', $a);
}

/**
* @param true $offset
*/
public function doBar7(bool $offset): void
{
$a = [false, false, false];
$a[$offset] = true;
assertType('array{false, true, false}', $a);
}

}

0 comments on commit 7ace968

Please sign in to comment.