Skip to content

Commit

Permalink
Refactor setAttribute function in a simpler way, to allow to set an…
Browse files Browse the repository at this point in the history
… array list as value for translation
  • Loading branch information
alipadron authored and freekmurze committed Dec 11, 2024
1 parent c55ea3c commit 859db44
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 10 deletions.
16 changes: 6 additions & 10 deletions src/HasTranslations.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,18 +49,14 @@ protected function mutateAttributeForArray($key, $value): mixed

public function setAttribute($key, $value)
{
if ($this->isTranslatableAttribute($key) && is_array($value)) {
return $this->setTranslations($key, $value);
}

// Pass arrays and untranslatable attributes to the parent method.
if (! $this->isTranslatableAttribute($key) || is_array($value)) {
return parent::setAttribute($key, $value);
if ($this->isTranslatableAttribute($key)) {
if (is_array($value) && ! array_is_list($value)) {
return $this->setTranslations($key, $value);
}
return $this->setTranslation($key, $this->getLocale(), $value);
}

// If the attribute is translatable and not already translated, set a
// translation for the current app locale.
return $this->setTranslation($key, $this->getLocale(), $value);
return parent::setAttribute($key, $value);
}

public function translate(string $key, string $locale = '', bool $useFallbackLocale = true): mixed
Expand Down
14 changes: 14 additions & 0 deletions tests/TranslatableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -906,3 +906,17 @@ public function setAttributesExternally(array $attributes)

expect($translations)->toEqual([]);
});

it('can set an array list as value for translation using `setTranslation`', function () {
$this->testModel->setTranslation('name', 'en', ['testValue_en']);
$this->testModel->save();

expect($this->testModel->getTranslation('name', 'en'))->toEqual(['testValue_en']);
});

it('can set an array list as value for translation using default local', function () {
$this->testModel->name = ['testValue_en'];
$this->testModel->save();

expect($this->testModel->getTranslation('name', 'en'))->toEqual(['testValue_en']);
});

0 comments on commit 859db44

Please sign in to comment.