diff --git a/src/needs-parens.mjs b/src/needs-parens.mjs index 2bd051fc0..c601bc78a 100644 --- a/src/needs-parens.mjs +++ b/src/needs-parens.mjs @@ -192,7 +192,12 @@ function needsParens(path, options) { case "bin": case "retif": if (key === "test" && !parent.trueExpr) { - return false; + // A full ternary in the test position of a shorthand ternary + // (`?:`) needs parens: `1 ? 2 : 3 ?: 4` is a syntax error in + // PHP 8. Shorthand ternaries chain left-associatively, so they + // don't need parens here. + // https://github.com/prettier/plugin-php/issues/2115 + return !!node.trueExpr; } return true; diff --git a/tests/retif/__snapshots__/jsfmt.spec.mjs.snap b/tests/retif/__snapshots__/jsfmt.spec.mjs.snap index 49603a8d0..5bf530738 100644 --- a/tests/retif/__snapshots__/jsfmt.spec.mjs.snap +++ b/tests/retif/__snapshots__/jsfmt.spec.mjs.snap @@ -212,6 +212,11 @@ $var = [ 'bar' => is_my_very_very_very_long() || !current_user_can("read") ? call_1() : call_2() ]; +var_dump((1 ? 2 : 3) ?: 4); +$var = (1 ? 2 : 3) ?: 4; +$var = (1 ?: 2) ?: 4; +$var = ($someOtherReallyReallyLongVariable ? $someOtherReallyReallyLongVariable : $someOtherReallyReallyLongVariable) ?: $someOtherReallyReallyLongVariable; + =====================================output===================================== is_my_very_long() || !current_user_can("read") ? call_1() : call_2(), 'bar' => is_my_very_very_very_long() || !current_user_can("read") ? call_1() : call_2() ]; + +var_dump((1 ? 2 : 3) ?: 4); +$var = (1 ? 2 : 3) ?: 4; +$var = (1 ?: 2) ?: 4; +$var = ($someOtherReallyReallyLongVariable ? $someOtherReallyReallyLongVariable : $someOtherReallyReallyLongVariable) ?: $someOtherReallyReallyLongVariable;