Skip to content
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
19 changes: 16 additions & 3 deletions src/UnderscoreTranslatable.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,32 @@

namespace Esign\UnderscoreTranslatable;

use Illuminate\Support\Facades\App;
use Illuminate\Support\Str;

trait UnderscoreTranslatable
{
protected ?string $translationLocale = null;

public function setLocale(string $locale): self
{
$this->translationLocale = $locale;

return $this;
}

public function getLocale(): string
{
return $this->translationLocale ?: config('app.locale');
}

public function isTranslatableAttribute(string $key): bool
{
return in_array($key, $this->getTranslatableAttributes());
}

public function getTranslatableAttributeName(string $key, ?string $locale = null): string
{
return $key . '_' . ($locale ?? App::getLocale());
return $key . '_' . ($locale ?? $this->getLocale());
}

public function getTranslation(string $key, ?string $locale = null, bool $useFallbackLocale = false): mixed
Expand Down Expand Up @@ -113,7 +126,7 @@ public function setAttribute($key, $value): mixed
}

if ($this->isTranslatableAttribute($key)) {
return $this->setTranslation($key, App::getLocale(), $value);
return $this->setTranslation($key, $this->getLocale(), $value);
}

return parent::setAttribute($key, $value);
Expand Down
29 changes: 28 additions & 1 deletion tests/UnderscoreTranslatableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,18 @@

final class UnderscoreTranslatableTest extends TestCase
{
#[Test]
public function it_can_set_and_get_the_translation_locale(): void
{
config(['app.locale' => 'en']);

$post = new Post();

$this->assertEquals('en', $post->getLocale());
$this->assertSame($post, $post->setLocale('nl'));
$this->assertEquals('nl', $post->getLocale());
}

#[Test]
public function it_can_check_if_an_attribute_is_translatable(): void
{
Expand Down Expand Up @@ -239,9 +251,24 @@ public function it_can_set_a_translatable_attribute_using_a_method(): void
public function it_can_set_a_translatable_attribute_using_a_property(): void
{
$post = new Post();
$post->setLocale('nl');
$post->title = 'Test en';

$this->assertEquals('Test en', $post->title_en);
$this->assertEquals('Test en', $post->title_nl);
}

#[Test]
public function it_can_get_a_translation_using_a_property_with_a_custom_model_locale(): void
{
$post = new Post();
$post->title_en = 'Test en';
$post->title_nl = 'Test nl';

$post->setLocale('nl');
$this->assertEquals('Test nl', $post->title);

$post->setLocale('en');
$this->assertEquals('Test en', $post->title);
}

#[Test]
Expand Down
Loading