Skip to content

Commit

Permalink
Prevent creation of duplicate terms on slug change (#384)
Browse files Browse the repository at this point in the history
* Fetch term by old slug if present

Signed-off-by: Philipp Daun <[email protected]>

* Add a test

---------

Signed-off-by: Philipp Daun <[email protected]>
Co-authored-by: Ryan Mitchell <[email protected]>
  • Loading branch information
daun and ryanmitchell authored Nov 20, 2024
1 parent 9b69409 commit b5ed5ba
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/Taxonomies/Term.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,11 @@ public static function makeModelFromContract(Contract $source)
}

return $class::firstOrNew([
'slug' => $source->slug(),
'slug' => $source->getOriginal('slug', $source->slug()),
'taxonomy' => $source->taxonomy(),
'site' => $source->locale(),
])->fill([
'slug' => $source->slug(),
'uri' => $source->uri(),
'data' => $data,
'updated_at' => $source->lastModified(),
Expand Down
32 changes: 32 additions & 0 deletions tests/Terms/TermTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace Tests\Terms;

use Illuminate\Foundation\Testing\RefreshDatabase;
use PHPUnit\Framework\Attributes\Test;
use Statamic\Eloquent\Taxonomies\Taxonomy;
use Statamic\Eloquent\Taxonomies\TermModel;
use Statamic\Facades\Term as TermFacade;
use Tests\TestCase;

class TermTest extends TestCase
{
use RefreshDatabase;

#[Test]
public function it_doesnt_create_a_new_model_when_slug_is_changed()
{
Taxonomy::make('test')->title('test')->save();

$term = tap(TermFacade::make('test-term')->taxonomy('test')->data([]))->save();

$this->assertCount(1, TermModel::all());
$this->assertSame('test-term', TermModel::first()->slug);

$term->slug('new-slug');
$term->save();

$this->assertCount(1, TermModel::all());
$this->assertSame('new-slug', TermModel::first()->slug);
}
}

0 comments on commit b5ed5ba

Please sign in to comment.