Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[9.x] Add method to extend localeArray generation #42275

Merged
merged 5 commits into from
May 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
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
22 changes: 21 additions & 1 deletion src/Illuminate/Translation/Translator.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,13 @@ class Translator extends NamespacedItemResolver implements TranslatorContract
*/
protected $selector;

/**
* The callable that should be invoked to determine applicable locales.
*
* @var callable
*/
protected $determineLocalesUsing;

/**
* Create a new translator instance.
*
Expand Down Expand Up @@ -325,7 +332,20 @@ public function parseKey($key)
*/
protected function localeArray($locale)
{
return array_filter([$locale ?: $this->locale, $this->fallback]);
$locales = array_filter([$locale ?: $this->locale, $this->fallback]);

return call_user_func($this->determineLocalesUsing ?: fn () => $locales, $locales);
}

/**
* Specify a callback that should be invoked to determined the applicable locale array.
*
* @param callable $callback
* @return void
*/
public function determineLocalesUsing($callback)
{
$this->determineLocalesUsing = $callback;
}

/**
Expand Down
14 changes: 14 additions & 0 deletions tests/Translation/TranslationTranslatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,20 @@ public function testEmptyFallbacks()
$this->assertSame('foo ', $t->get('foo :message', ['message' => null]));
}

public function testDetermineLocalesUsingMethod()
{
$t = new Translator($this->getLoader(), 'en');
$t->determineLocalesUsing(function ($locales) {
$this->assertSame(['en'], $locales);

return ['en', 'lz'];
});
$t->getLoader()->shouldReceive('load')->once()->with('en', '*', '*')->andReturn([]);
$t->getLoader()->shouldReceive('load')->once()->with('en', 'foo', '*')->andReturn([]);
$t->getLoader()->shouldReceive('load')->once()->with('lz', 'foo', '*')->andReturn([]);
$this->assertSame('foo', $t->get('foo'));
}

protected function getLoader()
{
return m::mock(Loader::class);
Expand Down