Skip to content
Permalink
Browse files

Improve support for null coalesce checks

  • Loading branch information
muglug committed Jan 14, 2020
1 parent b0073d4 commit e1daf26202ddb43721cdfdd29a280bc7ca6b46e5
@@ -393,33 +393,22 @@ public static function scrapeAssertions(
}

if ($conditional instanceof PhpParser\Node\Expr\BinaryOp\Coalesce) {
$var_name = ExpressionAnalyzer::getArrayVarId(
$conditional->left,
return self::scrapeAssertions(
new PhpParser\Node\Expr\Ternary(
new PhpParser\Node\Expr\Isset_(
[$conditional->left]
),
$conditional->left,
$conditional->right,
$conditional->getAttributes()
),
$this_class_name,
$source
$source,
$codebase,
$inside_negation,
false
);

if ($var_name) {
$if_types[$var_name] = [['isset']];
} else {
// look for any variables we *can* use for an isset assertion
$array_root = $conditional->left;

while ($array_root instanceof PhpParser\Node\Expr\ArrayDimFetch && !$var_name) {
$array_root = $array_root->var;

$var_name = ExpressionAnalyzer::getArrayVarId(
$array_root,
$this_class_name,
$source
);
}

if ($var_name) {
$if_types[$var_name] = [['=isset']];
}
}

return $if_types;
}

@@ -674,6 +674,7 @@ function (\Psalm\Internal\Clause $c) use ($mixed_var_ids) {
$naive_type = $statements_analyzer->node_data->getType($stmt->left);

if ($naive_type
&& !$naive_type->possibly_undefined
&& !$naive_type->hasMixed()
&& !$naive_type->isNullable()
) {
@@ -2273,7 +2273,13 @@ public function getGlobalType(string $var_id) : Type\Union
}

if ($this->isSuperGlobal($var_id)) {
return Type::getArray();
$type = Type::getArray();

if ($var_id === '$_SESSION') {
$type->possibly_undefined = true;
}

return $type;
}

return Type::getMixed();
@@ -96,7 +96,6 @@ public static function reconcile(
if (!$existing_var_type->isNullable()
&& $key
&& strpos($key, '[') === false
&& strpos($key, '->') === false
) {
foreach ($existing_var_type->getAtomicTypes() as $atomic) {
if (!$atomic instanceof TMixed
@@ -718,6 +718,30 @@ function foo() : void {
}
}',
],
'issetOnNullableObjectWithNullCoalesce' => [
'<?php
class A {
public bool $s = true;
}
function foo(?A $a) : string {
if (rand(0, 1) && !($a->s ?? false)) {
return "foo";
}
return "bar";
}',
],
'issetOnNullableObjectWithIsset' => [
'<?php
class A {
public bool $s = true;
}
function foo(?A $a) : string {
if (rand(0, 1) && !(isset($a->s) ? $a->s : false)) {
return "foo";
}
return "bar";
}',
],
];
}

0 comments on commit e1daf26

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