Skip to content

Commit 69ba9a2

Browse files
committed
Improve untag all query count and add phpdoc for properties
1 parent e0f68b3 commit 69ba9a2

File tree

3 files changed

+22
-5
lines changed

3 files changed

+22
-5
lines changed

src/IlluminateTag.php

+4
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,10 @@
2525
use Illuminate\Database\Eloquent\Relations\HasMany;
2626
use Illuminate\Database\Eloquent\Relations\MorphTo;
2727

28+
/** @property string $name */
29+
/** @property string $namespace */
30+
/** @property string $slug */
31+
/** @property int $count */
2832
class IlluminateTag extends Model
2933
{
3034
/**

src/TaggableTrait.php

+17-4
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,12 @@
2020

2121
namespace Cartalyst\Tags;
2222

23+
use Illuminate\Database\Eloquent\Collection;
2324
use Illuminate\Database\Eloquent\Model;
2425
use Illuminate\Database\Eloquent\Builder;
2526
use Illuminate\Database\Eloquent\Relations\MorphToMany;
2627

28+
/** @property Collection<IlluminateTag> $tags */
2729
trait TaggableTrait
2830
{
2931
/**
@@ -172,10 +174,19 @@ public function tag($tags): bool
172174
*/
173175
public function untag($tags = null): bool
174176
{
175-
$tags = $tags ?: $this->tags->pluck('name')->all();
176-
177-
foreach ($this->prepareTags($tags) as $tag) {
178-
$this->removeTag($tag);
177+
if (empty($tags)) {
178+
$tags = $this->tags;
179+
if (!empty($tags)) {
180+
$this->tags()->detach();
181+
foreach ($tags as $tag) {
182+
$tag->update(['count' => $tag->count - 1]);
183+
}
184+
$this->tags = new Collection();
185+
}
186+
} else {
187+
foreach ($this->prepareTags($tags) as $tag) {
188+
$this->removeTag($tag);
189+
}
179190
}
180191

181192
return true;
@@ -214,6 +225,7 @@ public function setTags($tags, string $type = 'name'): bool
214225
*/
215226
public function addTag(string $name): void
216227
{
228+
/** @var IlluminateTag $tag */
217229
$tag = $this->createTagsModel()->firstOrCreate([
218230
'slug' => $this->generateTagSlug($name),
219231
'namespace' => $this->getEntityClassName(),
@@ -242,6 +254,7 @@ public function removeTag(string $name): void
242254

243255
$namespace = $this->getEntityClassName();
244256

257+
/** @var IlluminateTag $tag */
245258
$tag = $this->tags()
246259
->whereNamespace($namespace)
247260
->where(function ($query) use ($name, $slug) {

tests/TaggableTraitTest.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ public function it_can_remove_all_tags()
8888
$queryCount = $this->withQueryCount(fn () => $post->untag());
8989

9090
$this->assertCount(0, $post->tags);
91-
$this->assertLessThanOrEqual(9, $queryCount);
91+
$this->assertLessThanOrEqual(4, $queryCount);
9292
}
9393

9494
#[Test]

0 commit comments

Comments
 (0)