Skip to content

Commit

Permalink
Fix incorrect locale usage when message ID is not exist
Browse files Browse the repository at this point in the history
  • Loading branch information
vjik committed Feb 22, 2024
1 parent be26af7 commit 5711afc
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 7 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## 3.0.1 under development

- Enh #131: Throw `InvalidArgumentException` when missed "one" plural key (@vjik)
- Bug #132: Fix incorrect locale usage when message ID is not exist (@vjik)

## 3.0.0 February 17, 2023

Expand Down
7 changes: 1 addition & 6 deletions src/Translator.php
Original file line number Diff line number Diff line change
Expand Up @@ -136,12 +136,7 @@ private function translateUsingCategorySources(
}
}

return end($this->categorySources[$category])->format(
$id,
$parameters,
$locale,
$this->defaultMessageFormatter
);
return $this->defaultMessageFormatter->format($id, $parameters, $locale);
}

private function dispatchMissingTranslationCategoryEvent(string $category): void
Expand Down
69 changes: 68 additions & 1 deletion tests/TranslatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -658,7 +658,74 @@ public function format(string $message, array $parameters, string $locale): stri

$this->assertSame(
$expectedMessage,
$translator->translate('test', [], $categorySource->getName())
$translator->translate('hello', [], $categorySource->getName())
);
}

public function dataDefaultMessageFormatterWithoutId(): array
{
return [
'without category' => [null],
'category with formatter' => [
new CategorySource(
'withFormatter',
$this->createMessageReader(
'withFormatter',
[
'withFormatter' => [
'en' => [
'hello' => 'Hello, {name}!',
],
],
]
),
new class () implements MessageFormatterInterface {
public function format(string $message, array $parameters, string $locale): string
{
return 'formatted by category';
}
},
),
],
'category without formatter' => [
new CategorySource(
'withoutFormatter',
$this->createMessageReader(
'withoutFormatter',
[
'withoutFormatter' => [
'en' => [
'hello' => 'Hello, {name}!',
],
],
]
),
),
],
];
}

/**
* @dataProvider dataDefaultMessageFormatterWithoutId
*/
public function testDefaultMessageFormatterWithoutId(?CategorySource $categorySource): void
{
$translator = new Translator(
locale: 'en',
defaultMessageFormatter: new class () implements MessageFormatterInterface {
public function format(string $message, array $parameters, string $locale): string
{
return 'formatted by translator';
}
},
);
if ($categorySource !== null) {
$translator->addCategorySources($categorySource);
}

$this->assertSame(
'formatted by translator',
$translator->translate('non-exist-id', [], 'test-category')
);
}

Expand Down

0 comments on commit 5711afc

Please sign in to comment.