Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 50 additions & 9 deletions src/Translator.php
Original file line number Diff line number Diff line change
Expand Up @@ -209,23 +209,64 @@ protected function getPluralIndex(?string $domain, int $n, bool $fallback): int
/**
* This function prepares the gettext plural form expression to be evaluated by PHP
*
* Nested ternary IFs will be enclosed by parenthesis and the variable "n" will be prefixed by "$".
* Both branches of every ternary IF will be enclosed by parenthesis (PHP does not
* allow nested ternaries without them) and the variable "n" will be prefixed by "$".
*
* $n==1 ? 0 : $n%10>=2 && $n%10<=4 && ($n%100<10 || $n%100>=20) ? 1 : 2
* n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2
* becomes
* $n==1 ? 0 : ($n%10>=2 && $n%10<=4 && ($n%100<10 || $n%100>=20) ? 1 : 2)
* $n==1 ?( 0 ):( $n%10>=2 && $n%10<=4 && ($n%100<10 || $n%100>=20) ?( 1 ):( 2))
*/
private static function fixTerseIfs(string $pluralForms): string
{
if (preg_match('/[^<>|%&!?:=n()\d\s]/', $pluralForms)) {
throw new InvalidArgumentException('Invalid plural form expression');
}
$pieces = explode(':', str_replace('n', '$n', $pluralForms));
$last = array_pop($pieces);
$pluralForms = '';
foreach ($pieces as $piece) {
$pluralForms .= "$piece:(";
$position = 0;
$code = static::parenthesizeTernaries($pluralForms, $position);
if ($position !== strlen($pluralForms)) {
// parsing stopped early on an unbalanced ")" or ":"
throw new InvalidArgumentException('Invalid plural form expression');
}
return $pluralForms . $last . str_repeat(')', count($pieces));

return str_replace('n', '$n', $code);
}

/**
* Reads a C conditional expression starting at $position, and returns it
* with both branches of each ternary IF enclosed by parenthesis.
* Stops at the end of the expression, or at a ")" or ":" closing an outer level.
*/
private static function parenthesizeTernaries(string $expression, int &$position): string
{
$length = strlen($expression);
$condition = '';
while ($position < $length) {
$char = $expression[$position];
if ($char === ')' || $char === ':') {
break;
}
$position++;
if ($char === '(') {
$condition .= '(' . static::parenthesizeTernaries($expression, $position);
if ($position >= $length || $expression[$position] !== ')') {
throw new InvalidArgumentException('Invalid plural form expression');
}
$condition .= ')';
$position++;
} elseif ($char === '?') {
$then = static::parenthesizeTernaries($expression, $position);
if ($position >= $length || $expression[$position] !== ':') {
throw new InvalidArgumentException('Invalid plural form expression');
}
$position++;
$else = static::parenthesizeTernaries($expression, $position);

return "$condition?($then):($else)";
} else {
$condition .= $char;
}
}

return $condition;
}
}
46 changes: 46 additions & 0 deletions tests/TranslatorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

namespace Gettext\Tests;

use Gettext\Translator;
use PHPUnit\Framework\TestCase;

class TranslatorTest extends TestCase
{
public function pluralFormsProvider(): array
{
return [
// Nested ternary in the "true" branch
['nplurals=3; plural=n != 1 ? (n == 2 ? 1 : 2) : 0;', [1 => 0, 2 => 1, 3 => 2, 0 => 2]],
// Nested ternary in the "true" branch, without parentheses
['nplurals=3; plural=n != 1 ? n == 2 ? 1 : 2 : 0;', [1 => 0, 2 => 1, 3 => 2, 0 => 2]],
// Nested ternaries in both branches
['nplurals=4; plural=n > 2 ? (n > 10 ? 3 : 2) : (n == 1 ? 0 : 1);', [0 => 1, 1 => 0, 2 => 1, 3 => 2, 11 => 3]],
// Chained ternaries in the "false" branch (the usual form)
['nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);', [1 => 0, 2 => 1, 5 => 2, 11 => 2, 21 => 0, 22 => 1, 25 => 2, 112 => 2]],
['nplurals=3; plural=(n % 10 == 1 && n % 100 != 11) ? 0 : ((n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 12 || n % 100 > 14)) ? 1 : 2);', [1 => 0, 3 => 1, 12 => 2, 24 => 1, 111 => 2]],
['nplurals=2; plural=n != 1;', [0 => 1, 1 => 0, 2 => 1]],
];
}

/**
* @dataProvider pluralFormsProvider
*/
public function testPluralForms(string $pluralForms, array $expected)
{
$translator = new Translator();
$translator->addTranslations([
'domain' => 'messages',
'plural-forms' => $pluralForms,
'messages' => [
'' => [
'apple' => ['form 0', 'form 1', 'form 2', 'form 3'],
],
],
]);

foreach ($expected as $n => $index) {
$this->assertSame("form $index", $translator->ngettext('apple', 'apples', $n), "n = $n");
}
}
}