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

Only allow variables greater than a number to be non-null

This commit is contained in:
Matthew Brown 2017-12-13 20:48:01 -05:00
parent e63441af1e
commit 298ee214e9
2 changed files with 50 additions and 2 deletions

View File

@ -642,6 +642,31 @@ class AssertionFinder
$other_type = isset($conditional->left->inferredType) ? $conditional->left->inferredType : null;
$var_type = isset($conditional->right->inferredType) ? $conditional->right->inferredType : null;
} elseif ($typed_value_position === self::ASSIGNMENT_TO_LEFT) {
$var_name = null;
} else {
throw new \UnexpectedValueException('$typed_value_position value');
}
if ($var_name) {
$if_types[$var_name] = '^isset';
}
return $if_types;
}
return [];
}
if ($conditional instanceof PhpParser\Node\Expr\BinaryOp\Smaller) {
$typed_value_position = self::hasTypedValueComparison($conditional);
if ($typed_value_position) {
$var_type = null;
$other_type = null;
if ($typed_value_position === self::ASSIGNMENT_TO_RIGHT) {
$var_name = null;
} elseif ($typed_value_position === self::ASSIGNMENT_TO_LEFT) {
/** @var PhpParser\Node\Expr $conditional->left */
$var_name = ExpressionChecker::getArrayVarId(

View File

@ -658,11 +658,16 @@ class TypeReconciliationTest extends TestCase
'$a' => 'int|null',
],
],
'eraseNullAfterGreaterThanCheck' => [
'eraseNullAfterInequalityCheck' => [
'<?php
$a = mt_rand(0, 1) ? mt_rand(0, 10) : null;
$a = mt_rand(0, 1) ? mt_rand(-10, 10) : null;
if ($a > 0) {
echo $a + 3;
}
if (0 < $a) {
echo $a + 3;
}',
],
];
@ -724,6 +729,24 @@ class TypeReconciliationTest extends TestCase
}',
'error_message' => 'TypeDoesNotContainType',
],
'dontEraseNullAfterLessThanCheck' => [
'<?php
$a = mt_rand(0, 1) ? mt_rand(-10, 10) : null;
if ($a < 0) {
echo $a + 3;
}',
'error_message' => 'PossiblyNullOperand',
],
'dontEraseNullAfterGreaterThanCheck' => [
'<?php
$a = mt_rand(0, 1) ? mt_rand(-10, 10) : null;
if (0 > $a) {
echo $a + 3;
}',
'error_message' => 'PossiblyNullOperand',
],
];
}
}