psalm icon indicating copy to clipboard operation
psalm copied to clipboard

Null coalescing assignment operator in if condition does not remove null from type

Open M393 opened this issue 1 year ago • 4 comments

https://psalm.dev/r/cdff4f688e All three functions should be without a warning as they all behave the same.

M393 avatar Nov 14 '24 14:11 M393

I found these snippets:

https://psalm.dev/r/cdff4f688e
<?php
function f(): object|null {
    return null;
}
function a(object|null $s): object {
    if (!($s ??= f())) {
        exit;
    }
    return $s;
}
function b(object|null $s): object {
    if (!$s && !($s = f())) {
        exit;
    }
    return $s;
}
function c(object|null $s): object {
    $s ??= f();
    if (!$s) {
        exit;
    }
    return $s;
}
Psalm output (using commit 03ee02c):

ERROR: NullableReturnStatement - 9:12 - The declared return type 'object' for a is not nullable, but the function returns 'null|object'

ERROR: InvalidNullableReturnType - 5:29 - The declared return type 'object' for a is not nullable, but 'null|object' contains null

psalm-github-bot[bot] avatar Nov 14 '24 14:11 psalm-github-bot[bot]

Ran into this as well.

Here's my attempt at a simpler example: https://psalm.dev/r/c2d540fb15

danielbeardsley avatar Aug 07 '25 20:08 danielbeardsley

I found these snippets:

https://psalm.dev/r/c2d540fb15
<?php

/** @var array<string, string> $a */
$a = [];

if ($a['missing'] ?? false) {
    echo $a['missing'];
}

if (isset($a['missing'])) {
    echo $a['missing'];
}
Psalm output (using commit cdceda0):

ERROR: RiskyTruthyFalsyComparison - 6:5 - Operand of type false|string contains type string, which can be falsy and truthy. This can cause possibly unexpected behavior. Use strict comparison instead.

INFO: PossiblyUndefinedStringArrayOffset - 7:10 - Possibly undefined array offset ''missing'' is risky given expected type 'string'. Consider using isset beforehand.

psalm-github-bot[bot] avatar Aug 07 '25 20:08 psalm-github-bot[bot]

@danielbeardsley That's a different issue: #9098

MoonE avatar Aug 08 '25 00:08 MoonE