Phpinspectionsea: Cast in null coalescing operand triggers suspicious binary operations inspection

Created on 15 Oct 2020  路  1Comment  路  Source: kalessil/phpinspectionsea


| Subject | Details |
| :------------- | :---------------------------------------------------------------------------- |
| Plugin | Php Inspections (EA Extended) 4.0.6 |
| Language level | PHP 7.4 |

Current behaviour

$y = '1'; $z = 2;

$x = (int) $y ?? $z;
//   ~~~~~~~~   [EA] The operation results to '(int) $y', please add missing parentheses. 

$x = ((int) $y) ?? $z;
//    ~~~~~~~~  [EA] The operation results to '(int) $y', please add missing parentheses. 

$x = (int) ($y ?? $z); // no error reported, but not what I want.

I assumed this inspection was intended to make explicit whether the cast was to be applied to the result of the entire null coalescing statement or just the first operand. Unfortunately adding clarifying parentheses does not remove the warning.

Expected behaviour

At least the second case with added parentheses should be valid.

In this particular case, I don't even think the clarifying parentheses should be required, so the first example should be valid as well. It is very obvious that a cast is applied to the next variable immediately following it and not the whole expression. The ?? provides a clear separation of intent. Of course this is a judgement call. I would rather not turn off the inspection entirely.

Environment details

IntelliJ IDEA 2020.2.3 (Ultimate Edition)
Build #IU-202.7660.26, built on October 6, 2020

Most helpful comment

The first and second examples don't make sense, because (int) $y evaluates to 0 if $y is null.
Thus, ?? $z would never be evaluated and could be removed.

This means only the third example is correct.

See: https://3v4l.org/rgVQQ

>All comments

The first and second examples don't make sense, because (int) $y evaluates to 0 if $y is null.
Thus, ?? $z would never be evaluated and could be removed.

This means only the third example is correct.

See: https://3v4l.org/rgVQQ

Was this page helpful?
0 / 5 - 0 ratings