Skip to content

Commit 55be6b3

Browse files
committed
Fixed tests & added new ones
1 parent 3192f76 commit 55be6b3

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

src/HasSlug.php

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,9 @@ public static function bootHasSlug()
2020
if($model->attributeIsTranslatable($attribute)) {
2121
$model->translateSlugs($attribute);
2222
} else {
23-
if(!is_null($model->attributes[$attribute])) return;
23+
if(!is_null($model->$attribute)) return;
2424

25+
$sluggable = $model->getSluggable();
2526
$model->attributes[$attribute] = str_slug($model->$sluggable);
2627
}
2728
});
@@ -35,7 +36,9 @@ public static function bootHasSlug()
3536
public function translateSlugs($attribute)
3637
{
3738
$sluggable = $this->getSluggable();
38-
$value = json_decode($this->attributes[$attribute], true);
39+
$value = isset($this->attributes[$attribute])
40+
? json_decode($this->attributes[$attribute], true)
41+
: [];
3942

4043
foreach($this->getTranslatedLocales($this->getSluggable()) as $locale) {
4144
if(!isset($value[$locale]) || is_null($value[$locale])) {

tests/SluggableTest.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,16 @@ public function test_it_saves_slug_on_model_save()
1111
$this->assertSame('my-test-title', $model->slug);
1212
}
1313

14+
public function test_it_does_not_overwrite_existing_slug()
15+
{
16+
$model = TestModel::create([
17+
'title' => 'My test title',
18+
'slug' => 'custom-slug'
19+
]);
20+
21+
$this->assertSame('custom-slug', $model->slug);
22+
}
23+
1424
public function test_it_saves_translated_slugs()
1525
{
1626
$model = TestModelTranslated::create([
@@ -25,6 +35,24 @@ public function test_it_saves_translated_slugs()
2535
$this->assertSame('mon-titre-test', $model->translate('slug', 'fr'));
2636
}
2737

38+
public function test_it_only_generates_missing_translated_slugs()
39+
{
40+
$model = TestModelTranslated::create([
41+
'title' => [
42+
'en' => 'My test title',
43+
'fr' => 'Mon titre test'
44+
],
45+
'slug' => [
46+
'en' => null,
47+
'fr' => 'custom-french-slug'
48+
]
49+
]);
50+
51+
$this->assertSame('{"en":"my-test-title","fr":"custom-french-slug"}', $model->getAttributes()['slug']);
52+
$this->assertSame('my-test-title', $model->slug);
53+
$this->assertSame('custom-french-slug', $model->translate('slug', 'fr'));
54+
}
55+
2856
public function test_can_override_sluggable_attribute()
2957
{
3058
$model = TestModelCustomAttribute::create(['title' => 'My test title']);

0 commit comments

Comments
 (0)