Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 30 additions & 4 deletions src/Locale/Locale.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,14 @@ class Locale
*/
public $default;

/**
* Fallback locale. Used when specific or default locale is missing translation.
* Should always be set to locale that includes all translations.
*
* @var string
*/
public $fallback;

/**
* Set New Locale from an array
*
Expand All @@ -44,7 +52,7 @@ public static function setLanguageFromArray(string $name, array $translations):
*/
public static function setLanguageFromJSON(string $name, string $path): void
{
if (! file_exists($path)) {
if (! file_exists($path) && self::$exceptions) {
throw new Exception('Translation file not found.');
}

Expand All @@ -55,13 +63,31 @@ public static function setLanguageFromJSON(string $name, string $path): void

public function __construct(string $default)
{
if (! \array_key_exists($default, self::$language)) {
if (! \array_key_exists($default, self::$language) && self::$exceptions) {
throw new Exception('Locale not found');
}

$this->default = $default;
}

/**
* Change fallback Locale
*
* @param $name
*
* @throws Exception
*/
public function setFallback(string $name): self
{
if (! \array_key_exists($name, self::$language) && self::$exceptions) {
throw new Exception('Locale not found');
}

$this->fallback = $name;

return $this;
}

/**
* Change Default Locale
*
Expand All @@ -71,7 +97,7 @@ public function __construct(string $default)
*/
public function setDefault(string $name): self
{
if (! \array_key_exists($name, self::$language)) {
if (! \array_key_exists($name, self::$language) && self::$exceptions) {
throw new Exception('Locale not found');
}

Expand All @@ -91,7 +117,7 @@ public function setDefault(string $name): self
*/
public function getText(string $key, array $placeholders = [])
{
$default = '{{'.$key.'}}';
$default = (self::$language[$this->fallback ?? ''] ?? [])[$key] ?? '{{'.$key.'}}';
Comment thread
Meldiron marked this conversation as resolved.
Outdated

if (! \array_key_exists($key, self::$language[$this->default])) {
if (self::$exceptions) {
Expand Down
13 changes: 13 additions & 0 deletions tests/Locale/LocaleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,4 +77,17 @@ public function testTexts(): void

$this->fail('No exception was thrown');
}

public function testFallback(): void
{
$locale = new Locale('he-IL');

$this->assertEquals('שלום', $locale->getText('hello'));
$this->assertEquals('{{world}}', $locale->getText('world'));

$locale->setFallback('en-US');

$this->assertEquals('שלום', $locale->getText('hello'));
$this->assertEquals('World', $locale->getText('world'));
}
}
Loading