Skip to content
New issue

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

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

Already on GitHub? # to your account

[11.x] Add replaceable tags to translations #51190

Merged
merged 3 commits into from
Apr 29, 2024
Merged
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
10 changes: 10 additions & 0 deletions src/Illuminate/Translation/Translator.php
Original file line number Diff line number Diff line change
@@ -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);
}
36 changes: 36 additions & 0 deletions tests/Translation/TranslationTranslatorTest.php
Original file line number Diff line number Diff line change
@@ -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');