False positive S836 Sonar Lint

  • Language: PHP
  • Rule: php:S836
  • It is a false-positive since the same operation but without a null coalescing assignment does not trigger the rule.
  • SonarQube for IDE - 10.13.1.80133
    • Not in a connected mode
  • Example:
class Example
{
    public static function example1(): string
    {
        static $value;

        $value ??= rand(0, 9) > 5 ? 'yes' : 'no';

        return $value;
    }

    public static function example2(): string {
        static $value;

        $value = $value ?? rand(0, 9) > 5 ? 'yes' : 'no';

        return $value;
    }
}

Hello @timur-hilmutdinov,

Thanks for raising awareness on this topic!

I checked locally, indeed the rule S836 is raising a FP on the case you presented.
I created a ticket to follow-up on this.

Just to mention, your above examples are not strictly equivalent.

In example1, $value will keep its value if it has one, otherwise it will be assigned with the result of rand(0, 9) > 5 ? 'yes' : 'no'.

In example2, because of Operator Precedence in PHP, it evaluate the ternary expression after the null coalescing check:

  1. $value ?? rand(0,9)
  2. above result > 5 ? 'yes' : 'no'

So when $value has a value, example1 and example2 will behave totally differently.

Thank you again for your message.
Best,
Rudy

1 Like