Skip to content

Commit

Permalink
[Feature] add replaceTranslations method which allows to replace all …
Browse files Browse the repository at this point in the history
…the translatios for a single key (#231)

Co-authored-by: Javier Ledezma <jledezma@medtrainer.com>
  • Loading branch information
javleds and jledezma-mt committed Oct 3, 2020
1 parent 865b47c commit 37ab2c7
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
22 changes: 22 additions & 0 deletions README.md
Expand Up @@ -176,6 +176,28 @@ $translations = [
$newsItem->setTranslations('name', $translations);
```

#### Replace translations in one go

You can replace all the translations for a single key using this method:

```php
public function replaceTranslations(string $key, array $translations)
```

Here's an example:

```php
$translations = ['en' => 'hello', 'es' => 'hola'];

$newsItem->setTranslations('hello', $translations);
$newsItem->getTranslations(); // ['en' => 'hello', 'es' => 'hola']

$newTranslations = ['en' => 'hello'];

$newsItem->replaceTranslations('hello', $newTranslations);
$newsItem->getTranslations(); // ['en' => 'hello']
```

#### Setting the model locale
The default locale used to translate models is the application locale,
however it can sometimes be handy to use a custom locale.
Expand Down
11 changes: 11 additions & 0 deletions src/HasTranslations.php
Expand Up @@ -164,6 +164,17 @@ public function hasTranslation(string $key, string $locale = null): bool
return isset($this->getTranslations($key)[$locale]);
}

public function replaceTranslations(string $key, array $translations): self
{
foreach ($this->getTranslatedLocales($key) as $locale) {
$this->forgetTranslation($key, $locale);
}

$this->setTranslations($key, $translations);

return $this;
}

protected function guardAgainstNonTranslatableAttribute(string $key)
{
if (! $this->isTranslatableAttribute($key)) {
Expand Down
14 changes: 14 additions & 0 deletions tests/TranslatableTest.php
Expand Up @@ -562,4 +562,18 @@ public function it_can_set_and_fetch_attributes_based_on_set_locale()
$this->testModel->setLocale('fr');
$this->assertSame($fr, $this->testModel->name);
}

/** @test */
public function it_can_replace_translations()
{
$translations = ['nl' => 'hallo', 'en' => 'hello', 'kh' => 'សួរស្តី'];

$this->testModel->setTranslations('name', $translations);
$this->testModel->save();

$newTranslations = ['es' => 'hola'];
$this->testModel->replaceTranslations('name', $newTranslations);

$this->assertEquals($newTranslations, $this->testModel->getTranslations('name'));
}
}

0 comments on commit 37ab2c7

Please sign in to comment.