Skip to content

Commit

Permalink
[9.x] Add method to extend localeArray generation (#42275)
Browse files Browse the repository at this point in the history
* Add method to extend localeArray generation

* style

* formatting

* move method

* formatting

Co-authored-by: Taylor Otwell <[email protected]>
  • Loading branch information
emiliopedrollo and taylorotwell authored May 5, 2022
1 parent 17c0fed commit c580f11
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
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

0 comments on commit c580f11

Please sign in to comment.