Skip to content

Commit

Permalink
Added a new method to allow fallbacks with translated attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
Egemen Berker Kızılcan committed Dec 31, 2015
1 parent 52c65f9 commit d6d4b1d
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 2 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"laravel",
"laravel5"
],
"version": "1.1.16",
"version": "1.1.17",
"authors": [
{
"name": "Hyleeh",
Expand Down
28 changes: 28 additions & 0 deletions src/Node.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand Down
2 changes: 1 addition & 1 deletion src/Providers/HierarchyServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

class HierarchyServiceProvider extends ServiceProvider {

const version = '1.1.16';
const version = '1.1.17';

/**
* Register the service provider.
Expand Down
41 changes: 41 additions & 0 deletions tests/NodeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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()
{
Expand Down

0 comments on commit d6d4b1d

Please sign in to comment.