Skip to content

Fix nested ternaries in the true branch of Plural-Forms - #15

Open
bardrop wants to merge 1 commit into
php-gettext:masterfrom
bardrop-oss:fix-nested-ternary-plural
Open

bardrop wants to merge 1 commit into
php-gettext:masterfrom
bardrop-oss:fix-nested-ternary-plural

Conversation

@bardrop

@bardrop bardrop commented Nov 21, 2026

Copy link
Copy Markdown

Fixes #14.

fixTerseIfs() split the plural expression on every : and wrapped the rest in parentheses. That only works when ternaries are nested in the "false" branch. With a nested ternary in the "true" branch (n != 1 ? (n == 2 ? 1 : 2) : 0, or the same without parentheses) the generated PHP is invalid and eval throws a ParseError on the first plural lookup.

This replaces the split with a small recursive reader: it walks the expression, follows (...) groups, and for each ?...: encloses both branches in parentheses. Everything else is copied as-is, and n still becomes $n. Unbalanced ) or : now throws the existing InvalidArgumentException instead of a ParseError from eval.

Tests: new tests/TranslatorTest.php with nested ternaries in the true branch, in both branches, the usual chained forms, and a 2-form rule. 3 cases fail on master with ParseError; all 17 tests pass with the change.

I also ran 626 plural expressions (real Plural-Forms headers plus random ternary/comparison mixes) against a C evaluator: no new differences, and the 5 ternary ParseErrors on master are gone.

fixTerseIfs() split the expression on every ':' and wrapped the rest
in parentheses, which only works when ternaries are nested in the
false branch. 'n != 1 ? (n == 2 ? 1 : 2) : 0' became invalid PHP and
threw a ParseError. Parse the expression instead and enclose both
branches of each ternary in parentheses.

Fixes php-gettext#14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Plural-Forms with a nested ternary in the true branch throws ParseError

1 participant