diff --git a/src/Date.php b/src/Date.php index 449948b..db1bcba 100644 --- a/src/Date.php +++ b/src/Date.php @@ -377,11 +377,26 @@ public static function getLocale() public static function setLocale($locale) { // Use RFC 5646 for filenames. - $resource = __DIR__.'/Lang/'.str_replace('_', '-', $locale).'.php'; + $files = array_unique([ + str_replace('_', '-', $locale), + static::getLanguageFromLocale($locale), + str_replace('_', '-', static::getFallbackLocale()), + static::getLanguageFromLocale(static::getFallbackLocale()), + ]); - if (! file_exists($resource)) { - static::setLocale(static::getFallbackLocale()); + $found = false; + foreach ($files as $file) { + $resource = __DIR__.'/Lang/'.$file.'.php'; + + if (file_exists($resource)) { + $found = true; + $locale = $file; + break; + } + } + + if (! $found) { return; } @@ -505,4 +520,17 @@ public static function translateTimeString($time) return $translated; } + + /** + * Get the language portion of the locale. + * + * @param string $locale + * @return string + */ + public static function getLanguageFromLocale($locale) + { + $parts = explode('_', str_replace('-', '_', $locale)); + + return $parts[0]; + } } diff --git a/tests/TranslationTest.php b/tests/TranslationTest.php index 2523840..b482f21 100644 --- a/tests/TranslationTest.php +++ b/tests/TranslationTest.php @@ -30,6 +30,15 @@ public function testFallback() $this->assertSame('5 years ago', $date->ago()); } + public function testFallbackWithRegion() + { + Date::setFallbackLocale('en_US'); + Date::setLocale('xx'); + + $date = Date::parse('-5 years'); + $this->assertSame('5 years ago', $date->ago()); + } + public function testMultiplePluralForms() { Date::setLocale('hr');