diff --git a/CHANGELOG.md b/CHANGELOG.md index 00006f6..c2d8626 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 category source is not exist and specified fallback locale (@vjik) ## 3.0.0 February 17, 2023 diff --git a/src/Translator.php b/src/Translator.php index df0fcd8..880f98d 100644 --- a/src/Translator.php +++ b/src/Translator.php @@ -81,7 +81,7 @@ public function translate( if (empty($this->categorySources[$category])) { $this->dispatchMissingTranslationCategoryEvent($category); - return $this->defaultMessageFormatter->format((string) $id, $parameters, $locale); + return $this->defaultMessageFormatter->format((string) $id, $parameters, $this->fallbackLocale ?? $locale); } return $this->translateUsingCategorySources((string) $id, $parameters, $category, $locale); diff --git a/tests/TranslatorTest.php b/tests/TranslatorTest.php index 83dcba8..70ec6f1 100644 --- a/tests/TranslatorTest.php +++ b/tests/TranslatorTest.php @@ -662,6 +662,43 @@ public function format(string $message, array $parameters, string $locale): stri ); } + public static function dataDefaultMessageFormatterWithoutCategory(): array + { + return [ + 'another-fallback-locale' => [ + '(en)', + 'en', + ], + 'same-fallback-locale' => [ + '(ru)', + 'ru', + ], + 'without-fallback-locale' => [ + '(ru)', + null, + ], + ]; + } + + /** + * @dataProvider dataDefaultMessageFormatterWithoutCategory + */ + public function testDefaultMessageFormatterWithoutCategory(string $expected, ?string $fallbackLocale) + { + $translator = new Translator( + locale: 'ru', + fallbackLocale: $fallbackLocale, + defaultMessageFormatter: new class () implements MessageFormatterInterface { + public function format(string $message, array $parameters, string $locale): string + { + return '(' . $locale . ')'; + } + }, + ); + + $this->assertSame($expected, $translator->translate('test')); + } + public function testFluentInterface(): void { $translator = new Translator();