diff --git a/composer.json b/composer.json index ef60794..f1a7be1 100644 --- a/composer.json +++ b/composer.json @@ -13,7 +13,7 @@ "laravel", "laravel5" ], - "version": "1.1.16", + "version": "1.1.17", "authors": [ { "name": "Hyleeh", diff --git a/src/Node.php b/src/Node.php index 1ef1304..d236b0d 100644 --- a/src/Node.php +++ b/src/Node.php @@ -218,6 +218,34 @@ public function getNewTranslation($locale) return $nodeSource; } + /** + * Returns a translation attribute + * (optionally with fallback) + * + * @param string $key + * @param string $locale + * @param bool $fallback + * @return string|null + */ + public function getTranslationAttribute($key, $locale = null, $fallback = true) + { + if ($this->isTranslationAttribute($key)) + { + $locale = $locale ?: $this->locale(); + + $attribute = $this->translate($locale)->$key; + + if (empty($attribute) && $fallback) + { + $attribute = $this->translate($this->getFallbackLocale())->$key; + } + + return $attribute; + } + + return null; + } + /** * Published scope * diff --git a/src/Providers/HierarchyServiceProvider.php b/src/Providers/HierarchyServiceProvider.php index 3c64222..aa6d9d9 100644 --- a/src/Providers/HierarchyServiceProvider.php +++ b/src/Providers/HierarchyServiceProvider.php @@ -8,7 +8,7 @@ class HierarchyServiceProvider extends ServiceProvider { - const version = '1.1.16'; + const version = '1.1.17'; /** * Register the service provider. diff --git a/tests/NodeTest.php b/tests/NodeTest.php index 6cf0adc..ce10f21 100644 --- a/tests/NodeTest.php +++ b/tests/NodeTest.php @@ -291,6 +291,47 @@ function it_gets_locale_for_node_name() ); } + /** @test */ + function it_gets_translated_attributes_with_fallback() + { + $node = $this->getNode(); + $node->{'node_name:en'} = 'about'; + $node->{'node_name:tr'} = ''; + + $this->assertEquals( + $node->getTranslationAttribute('node_name'), + 'about' + ); + + $this->assertEquals( + $node->getTranslationAttribute('node_name', 'tr'), + 'about' + ); + + $this->assertEquals( + $node->getTranslationAttribute('node_name', 'tr', false), + '' + ); + + $this->assertNull( + $node->getTranslationAttribute('created_at', 'tr', false) + ); + + app()->setLocale('tr'); + + $this->assertEquals( + $node->getTranslationAttribute('node_name'), + 'about' + ); + + $node->{'node_name:tr'} = 'hakkinda'; + + $this->assertEquals( + $node->getTranslationAttribute('node_name'), + 'hakkinda' + ); + } + /** @test */ function it_checks_translated_children() {