From 476e0ea1f78fe4ef07e3d6cdc247b0e673c5e044 Mon Sep 17 00:00:00 2001 From: Tom Witkowski Date: Tue, 24 Jul 2018 17:50:16 +0200 Subject: [PATCH] use fallback in attributesToArray (#503) * use fallback in attributesToArray #448 * fix empty line * define locale that's not present * fix getAttributeOrFallback() * fix php cs --- src/Translatable/Translatable.php | 22 +++++++++++++--------- tests/TranslatableTest.php | 1 + 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/src/Translatable/Translatable.php b/src/Translatable/Translatable.php index aa786d7..4b7cce5 100644 --- a/src/Translatable/Translatable.php +++ b/src/Translatable/Translatable.php @@ -162,17 +162,23 @@ private function usePropertyFallback() */ private function getAttributeOrFallback($locale, $attribute) { - $value = $this->getTranslation($locale)->$attribute; + $translation = $this->getTranslation($locale); if ( - empty($value) && - $this->usePropertyFallback() && - ($fallback = $this->getTranslation($this->getFallbackLocale(), true)) + ( + ! $translation instanceof Model || + empty($translation->$attribute) + ) && + $this->usePropertyFallback() ) { - return $fallback->$attribute; + $translation = $this->getTranslation($this->getFallbackLocale(), true); } - return $value; + if ($translation instanceof Model) { + return $translation->$attribute; + } + + return null; } /** @@ -723,9 +729,7 @@ public function attributesToArray() continue; } - if ($translations = $this->getTranslation()) { - $attributes[$field] = $translations->$field; - } + $attributes[$field] = $this->getAttributeOrFallback(null, $field); } return $attributes; diff --git a/tests/TranslatableTest.php b/tests/TranslatableTest.php index 97db98a..16651f9 100644 --- a/tests/TranslatableTest.php +++ b/tests/TranslatableTest.php @@ -422,6 +422,7 @@ public function test_fallback_for_country_based_locales_with_no_base_locale() public function test_to_array_and_fallback_with_country_based_locales_enabled() { + $this->app->config->set('translatable.locale', 'en-GB'); $this->app->config->set('translatable.use_fallback', true); $this->app->config->set('translatable.fallback_locale', 'fr'); $this->app->config->set('translatable.locales', ['en' => ['GB'], 'fr']);