1
0
mirror of https://github.com/danog/psalm.git synced 2024-11-30 04:39:00 +01:00

Fix #4061 - allow indirect null comparison check

This commit is contained in:
Brown 2020-08-26 17:58:01 -04:00 committed by Daniil Gentili
parent 489cd99752
commit 5835eec863
Signed by: danog
GPG Key ID: 8C1BE3B34B230CA7
2 changed files with 33 additions and 4 deletions

View File

@ -511,7 +511,7 @@ class AssertionFinder
) { ) {
$if_types = []; $if_types = [];
$null_position = self::hasNullVariable($conditional); $null_position = self::hasNullVariable($conditional, $source);
$false_position = self::hasFalseVariable($conditional); $false_position = self::hasFalseVariable($conditional);
$true_position = self::hasTrueVariable($conditional); $true_position = self::hasTrueVariable($conditional);
$empty_array_position = self::hasEmptyArrayVariable($conditional); $empty_array_position = self::hasEmptyArrayVariable($conditional);
@ -1147,7 +1147,7 @@ class AssertionFinder
) { ) {
$if_types = []; $if_types = [];
$null_position = self::hasNullVariable($conditional); $null_position = self::hasNullVariable($conditional, $sourcec);
$false_position = self::hasFalseVariable($conditional); $false_position = self::hasFalseVariable($conditional);
$true_position = self::hasTrueVariable($conditional); $true_position = self::hasTrueVariable($conditional);
$empty_array_position = self::hasEmptyArrayVariable($conditional); $empty_array_position = self::hasEmptyArrayVariable($conditional);
@ -2439,8 +2439,10 @@ class AssertionFinder
* *
* @return int|null * @return int|null
*/ */
protected static function hasNullVariable(PhpParser\Node\Expr\BinaryOp $conditional) protected static function hasNullVariable(
{ PhpParser\Node\Expr\BinaryOp $conditional,
FileSource $source
) {
if ($conditional->right instanceof PhpParser\Node\Expr\ConstFetch if ($conditional->right instanceof PhpParser\Node\Expr\ConstFetch
&& strtolower($conditional->right->name->parts[0]) === 'null' && strtolower($conditional->right->name->parts[0]) === 'null'
) { ) {
@ -2453,6 +2455,13 @@ class AssertionFinder
return self::ASSIGNMENT_TO_LEFT; return self::ASSIGNMENT_TO_LEFT;
} }
if ($source instanceof StatementsAnalyzer
&& ($right_type = $source->node_data->getType($conditional->right))
&& $right_type->isNull()
) {
return self::ASSIGNMENT_TO_RIGHT;
}
return null; return null;
} }

View File

@ -736,6 +736,26 @@ class ValueTest extends \Psalm\Tests\TestCase
} }
if ($data["e"] > 0) {}' if ($data["e"] > 0) {}'
], ],
'compareToNullImplicitly' => [
'<?php
final class Foo {
public const VALUE_ANY = null;
public const VALUE_ONE = "one";
/** @return self::VALUE_* */
public static function getValues() {
return rand(0, 1) ? null : self::VALUE_ONE;
}
}
$data = Foo::getValues();
if ($data === Foo::VALUE_ANY) {
$data = "default";
}
echo strlen($data);'
],
]; ];
} }