diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 1638df3..6652d0f 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -760,11 +760,6 @@ parameters: count: 1 path: src/lib/UserSetting/Setting/FullDateTimeFormat.php - - - message: "#^Method Ibexa\\\\User\\\\UserSetting\\\\Setting\\\\Language\\:\\:getDefaultValue\\(\\) should return string but returns string\\|false\\.$#" - count: 1 - path: src/lib/UserSetting/Setting/Language.php - - message: "#^Method Ibexa\\\\User\\\\UserSetting\\\\Setting\\\\ShortDateTimeFormat\\:\\:getDefaultValue\\(\\) should return string but returns string\\|null\\.$#" count: 1 diff --git a/src/lib/UserSetting/Setting/Language.php b/src/lib/UserSetting/Setting/Language.php index 713563c..6290f93 100644 --- a/src/lib/UserSetting/Setting/Language.php +++ b/src/lib/UserSetting/Setting/Language.php @@ -72,9 +72,16 @@ public function getDisplayValue(string $storageValue): string */ public function getDefaultValue(): string { + $defaultLocale = ''; $preferredLocales = $this->userLanguagePreferenceProvider->getPreferredLocales(); - return reset($preferredLocales); + $list = $this->availableLocaleChoiceLoader->getChoiceList(); + $commonLocales = array_intersect($preferredLocales, $list); + if (!empty($commonLocales)) { + $defaultLocale = reset($commonLocales); + } + + return $defaultLocale; } /** diff --git a/tests/lib/UserSetting/Setting/LanguageTest.php b/tests/lib/UserSetting/Setting/LanguageTest.php new file mode 100644 index 0000000..0a39aa1 --- /dev/null +++ b/tests/lib/UserSetting/Setting/LanguageTest.php @@ -0,0 +1,67 @@ +userLanguagePreferenceProvider = $this->createMock( + UserLanguagePreferenceProviderInterface::class + ); + $this->availableLocaleChoiceLoader = $this->createMock( + AvailableLocaleChoiceLoader::class + ); + } + + /** + * @dataProvider providerForDefaultValue + * + * @param string[] $availableLocales + * @param string[] $preferredLocales + */ + public function testGetDefaultValue( + array $preferredLocales, + array $availableLocales, + string $expectedDefaultValue + ): void { + $this->userLanguagePreferenceProvider->method('getPreferredLocales')->willReturn($preferredLocales); + $this->availableLocaleChoiceLoader->method('getChoiceList')->willReturn($availableLocales); + + $language = new Language( + $this->createMock(TranslatorInterface::class), + $this->userLanguagePreferenceProvider, + $this->availableLocaleChoiceLoader, + ); + + self::assertSame($expectedDefaultValue, $language->getDefaultValue()); + } + + /** + * @return iterable> + */ + public function providerForDefaultValue(): iterable + { + yield 'intersection' => [['en_GB', 'en'], ['en', 'de', 'el', 'en_US'], 'en']; + yield 'no available locale' => [['en_GB', 'en'], ['de', 'el', 'en_US'], '']; + yield 'user preferred language priority' => [['en_GB', 'en', 'de'], ['de', 'en', 'el'], 'en']; + } +}