Skip to content
Permalink
Browse files

Typecast bool to int (#2550)

* adding specific checks for typecasting booleans, re: #2548

* satisfying phpcs

* amend check to use psalm types rather than php-parser types

* implementing tests for typecasting bools to int

* satisfying phpcs
  • Loading branch information
SignpostMarv authored and muglug committed Jan 4, 2020
1 parent 26a8956 commit fbf66ba7f683f3956b547c5424c257dc94bc9a2a
@@ -72,6 +72,7 @@
use function array_merge;
use function array_values;
use function array_map;
use function current;

/**
* @internal
@@ -555,7 +556,24 @@ public static function analyze(
return false;
}

$statements_analyzer->node_data->setType($stmt, Type::getInt());
$as_int = true;
$maybe_type = $statements_analyzer->node_data->getType($stmt->expr);

if (null !== $maybe_type) {
$maybe = $maybe_type->getAtomicTypes();

if (1 === count($maybe) && current($maybe) instanceof Type\Atomic\TBool) {
$as_int = false;
$statements_analyzer->node_data->setType($stmt, new Type\Union([
new Type\Atomic\TLiteralInt(0),
new Type\Atomic\TLiteralInt(1),
]));
}
}

if ($as_int) {
$statements_analyzer->node_data->setType($stmt, Type::getInt());
}
} elseif ($stmt instanceof PhpParser\Node\Expr\Cast\Double) {
if (self::analyze($statements_analyzer, $stmt->expr, $context) === false) {
return false;
@@ -656,6 +656,39 @@ class A {
private $type = "easy";
}'
],
'typecastTrueToInt' => [
'<?php
/**
* @param 0|1 $int
*/
function foo(int $int) : void {
echo (string) $int;
}
foo((int) true);',
],
'typecastFalseToInt' => [
'<?php
/**
* @param 0|1 $int
*/
function foo(int $int) : void {
echo (string) $int;
}
foo((int) false);',
],
'typecastedBoolToInt' => [
'<?php
/**
* @param 0|1 $int
*/
function foo(int $int) : void {
echo (string) $int;
}
foo((int) ((bool) 2));',
],
];
}

0 comments on commit fbf66ba

Please sign in to comment.
You can’t perform that action at this time.