From 3215a722a39f4ed1a04ad7c0edde7691abf42e66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?An=C5=BEe=20=C4=8Casar?= Date: Tue, 25 Oct 2016 00:01:57 +0200 Subject: [PATCH] Fix dirty translatable attributes --- src/Translatable.php | 38 ++++++++++++++++++++++++++++++++++++++ tests/TestCRUD.php | 13 +++++++++++++ 2 files changed, 51 insertions(+) diff --git a/src/Translatable.php b/src/Translatable.php index ac5f9b1..1230018 100644 --- a/src/Translatable.php +++ b/src/Translatable.php @@ -12,6 +12,8 @@ trait Translatable protected $overrideWithFallback = null; + protected $localeChanged = false; + /** * Translated attributes cache * @@ -287,6 +289,8 @@ public function setLocale($locale) { $this->overrideLocale = $locale; + $this->localeChanged = true; + return $this; } @@ -464,4 +468,38 @@ protected function newBaseQueryBuilder() return $builder->setModel($this); } + + /** + * Get the attributes that have been changed since last sync. + * + * @return array + */ + public function getDirty() + { + $dirty = parent::getDirty(); + + if(! $this->localeChanged) { + return $dirty; + } + + foreach ($this->translatableAttributes() as $key) { + if(isset($this->attributes[$key])) { + $dirty[$key] = $this->attributes[$key]; + } + } + + return $dirty; + } + + /** + * Sync the original attributes with the current. + * + * @return $this + */ + public function syncOriginal() + { + $this->localeChanged = false; + + return parent::syncOriginal(); + } } \ No newline at end of file diff --git a/tests/TestCRUD.php b/tests/TestCRUD.php index e84243f..4ab7b61 100644 --- a/tests/TestCRUD.php +++ b/tests/TestCRUD.php @@ -34,6 +34,19 @@ public function testModelCanBeStoredAndRetrievedInDifferentLocales() $this->assertEquals('DE Lorem ipsum', $user->bio); } + public function testModelWithIdenticalTranslationsIsSaved() + { + User::forceCreate([ + 'name' => 'John Doe' + ], [ + 'en' => ['bio' => 'Sample bio'], + 'de' => ['bio' => 'Sample bio'], + ]); + + $this->assertEquals('Sample bio', User::withoutFallback()->onlyTranslated('en')->first()->bio); + $this->assertEquals('Sample bio', User::withoutFallback()->onlyTranslated('de')->first()->bio); + } + public function testFallbackLocaleIsUsedWhenNoMatchingLocaleIsFound() { User::forceCreate([