Skip to content

SimplifyIfElseToTernaryRector doesn't honor operator precedence #9081

@noother

Description

@noother

Bug Report

Subject Details
Rector version last dev-main
Installed as composer dependency

Minimal PHP Code Causing Issue

See https://getrector.com/demo/0571b41e-9b58-452d-a32c-1840af3d8784

<?php

$foo = rand(0,1);
$bar = rand(0,1);

if($foo and $bar) {
    $baz = '1';
} else {
    $baz = '2';
}

Responsible rules

  • SimplifyIfElseToTernaryRector

Expected Behavior

It should change the code to

$baz = ($foo and $bar) ? '1' : '2';

to keep logic intact.

However, it changes the code to

$baz = $foo and $bar ? '1' : '2';

without the parentheses, which would be correct, if && was used instead of "and" here, but
due to PHP operator precedence, this code now effectively becomes:

$baz = $foo;
if($foo) {
    $bar ? '1' : '2'; // This does nothing
}

Now $baz contains the value of $foo instead of the supposed result of the condition.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions