Skip to content

Commit

Permalink
In SimpleMessageFormatter add support of messages where used parame…
Browse files Browse the repository at this point in the history
…ters with plural modifier that contain non-supported keys (#99)
  • Loading branch information
vjik committed Nov 29, 2022
1 parent 2283b93 commit 3aead8d
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 12 deletions.
3 changes: 2 additions & 1 deletion CHANGELOG.md
Expand Up @@ -2,7 +2,8 @@

## 2.2.1 under development

- no changes in this release.
- Enh #99: In `SimpleMessageFormatter` add support of messages where used parameters with plural modifier that contain
non-supported keys (@vjik)

## 2.2.0 November 28, 2022

Expand Down
9 changes: 3 additions & 6 deletions src/SimpleMessageFormatter.php
Expand Up @@ -77,17 +77,14 @@ private static function pluralize(mixed $value, string $options): string
$map = [];
foreach ($pluralMatches[1] as $index => $match) {
if (!in_array($match, self::PLURAL_KEYS, true)) {
$keysStr = self::formatList(self::PLURAL_KEYS);

throw new InvalidArgumentException("Invalid plural key - \"$match\". The valid keys are $keysStr.");
continue;
}

$map[$match] = $pluralMatches[3][$index];
}

$diff = array_diff(self::PLURAL_KEYS, $pluralMatches[1]);
if ($diff !== []) {
throw new InvalidArgumentException('Missing plural keys: ' . self::formatList($diff) . '.');
if (!in_array(self::PLURAL_OTHER, $pluralMatches[1], true)) {
throw new InvalidArgumentException('Missing plural key "' . self::PLURAL_OTHER . '".');
}

return $value === 1 ? $map[self::PLURAL_ONE] : $map[self::PLURAL_OTHER];
Expand Down
10 changes: 5 additions & 5 deletions tests/SimpleMessageFormatterTest.php
Expand Up @@ -77,13 +77,13 @@ public function testFormat(string $message, array $parameters, string $expected)
$this->assertEquals($expected, $result);
}

public function testFormatPluralWithWrongKey(): void
public function testFormatPluralWithNotSupportedKey(): void
{
$formatter = new SimpleMessageFormatter();

$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid plural key - "many". The valid keys are "one", "other".');
$formatter->format('{min, plural, one{character} many{characters}}', ['min' => 1]);
$result = $formatter->format('{min, plural, one{character} many{characters} other{characters}}', ['min' => 2]);

$this->assertSame('characters', $result);
}

public function testFormatPluralWithNonInteger(): void
Expand All @@ -100,7 +100,7 @@ public function testFormatPluralWithMissingKey(): void
$formatter = new SimpleMessageFormatter();

$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Missing plural keys: "other".');
$this->expectExceptionMessage('Missing plural key "other".');
$formatter->format('{min, plural, one{character}}', ['min' => 1]);
}

Expand Down

0 comments on commit 3aead8d

Please sign in to comment.