Skip to content

Commit

Permalink
[11.x] Add replaceable tags to translations (#51190)
Browse files Browse the repository at this point in the history
* feat: add replaceable tags to translations

* Update Translator.php

* Update Translator.php

---------

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
LegendEffects and taylorotwell committed Apr 29, 2024
1 parent e38d945 commit 83e1f56
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/Illuminate/Translation/Translator.php
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,16 @@ protected function makeReplacements($line, array $replace)
$shouldReplace = [];

foreach ($replace as $key => $value) {
if ($value instanceof Closure) {
$line = preg_replace_callback(
'/<'.$key.'>(.*?)<\/'.$key.'>/',
fn ($args) => $value($args[1]),
$line
);

continue;
}

if (is_object($value) && isset($this->stringableHandlers[get_class($value)])) {
$value = call_user_func($this->stringableHandlers[get_class($value)], $value);
}
Expand Down
36 changes: 36 additions & 0 deletions tests/Translation/TranslationTranslatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,42 @@ public function testGetJsonReplacesWithStringable()
);
}

public function testTagReplacements()
{
$t = new Translator($this->getLoader(), 'en');

$t->getLoader()->shouldReceive('load')->once()->with('en', '*', '*')->andReturn([]);
$t->getLoader()->shouldReceive('load')->once()->with('en', 'We have some nice <docs-link>documentation</docs-link>', '*')->andReturn([]);

$this->assertSame(
'We have some nice <a href="https://laravel.com/docs">documentation</a>',
$t->get(
'We have some nice <docs-link>documentation</docs-link>',
[
"docs-link" => fn ($children) => "<a href=\"https://laravel.com/docs\">$children</a>"
]
)
);
}

public function testTagReplacementsHandleMultipleOfSameTag()
{
$t = new Translator($this->getLoader(), 'en');

$t->getLoader()->shouldReceive('load')->once()->with('en', '*', '*')->andReturn([]);
$t->getLoader()->shouldReceive('load')->once()->with('en', '<bold-this>bold</bold-this> something else <bold-this>also bold</bold-this>', '*')->andReturn([]);

$this->assertSame(
'<b>bold</b> something else <b>also bold</b>',
$t->get(
'<bold-this>bold</bold-this> something else <bold-this>also bold</bold-this>',
[
"bold-this" => fn ($children) => "<b>$children</b>"
]
)
);
}

public function testDetermineLocalesUsingMethod()
{
$t = new Translator($this->getLoader(), 'en');
Expand Down

0 comments on commit 83e1f56

Please sign in to comment.