Skip to content

Commit

Permalink
Track variable usage in bool to int casts (#5349)
Browse files Browse the repository at this point in the history
Fixes #4956
  • Loading branch information
weirdan authored Mar 11, 2021
1 parent 185827a commit 8be77aa
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/Psalm/Internal/Analyzer/Statements/Expression/CastAnalyzer.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,18 @@ public static function analyze(

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

if ($statements_analyzer->data_flow_graph
&& $statements_analyzer->data_flow_graph instanceof \Psalm\Internal\Codebase\VariableUseGraph
) {
$type->parent_nodes = $maybe_type->parent_nodes;
}

$statements_analyzer->node_data->setType($stmt, $type);
}
}

Expand Down
12 changes: 12 additions & 0 deletions tests/UnusedVariableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2316,6 +2316,18 @@ function createFailingFunction(RuntimeException $exception): Closure
};
}
',
],
'usedInIntCastInAssignment' => [
'<?php
/** @return mixed */
function f() {
$a = random_int(0, 10) >= 5 ? true : false;
$b = (int) $a;
return $b;
}
'
]
];
}
Expand Down

0 comments on commit 8be77aa

Please sign in to comment.