Completed
Push — master ( 3fa0ab...4d90c4 )
by Freek
01:09
created

src/HasTags.php (12 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Spatie\Tags;
4
5
use InvalidArgumentException;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Database\Eloquent\Builder;
8
use Illuminate\Database\Eloquent\Collection;
9
use Illuminate\Database\Eloquent\Relations\MorphToMany;
10
11
trait HasTags
12
{
13
    protected $queuedTags = [];
14
15
    public static function getTagClassName(): string
16
    {
17
        return Tag::class;
18
    }
19
20
    public static function bootHasTags()
21
    {
22
        static::created(function (Model $taggableModel) {
23
            if (count($taggableModel->queuedTags) > 0) {
24
                $taggableModel->attachTags($taggableModel->queuedTags);
25
26
                $taggableModel->queuedTags = [];
27
            }
28
        });
29
30
        static::deleted(function (Model $deletedModel) {
31
            $tags = $deletedModel->tags()->get();
32
33
            $deletedModel->detachTags($tags);
34
        });
35
    }
36
37
    public function tags(): MorphToMany
38
    {
39
        return $this
0 ignored issues
show
It seems like morphToMany() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
40
            ->morphToMany(self::getTagClassName(), 'taggable')
41
            ->ordered();
42
    }
43
44
    /**
45
     * @param string $locale
46
     */
47
    public function tagsTranslated($locale = null): MorphToMany
48
    {
49
        $locale = ! is_null($locale) ? $locale : app()->getLocale();
50
51
        return $this
0 ignored issues
show
It seems like morphToMany() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
52
            ->morphToMany(self::getTagClassName(), 'taggable')
53
            ->select('*')
54
            ->selectRaw("JSON_UNQUOTE(JSON_EXTRACT(name, '$.\"{$locale}\"')) as name_translated")
55
            ->selectRaw("JSON_UNQUOTE(JSON_EXTRACT(slug, '$.\"{$locale}\"')) as slug_translated")
56
            ->ordered();
57
    }
58
59
    /**
60
     * @param string|array|\ArrayAccess|\Spatie\Tags\Tag $tags
61
     */
62
    public function setTagsAttribute($tags)
63
    {
64
        if (! $this->exists) {
0 ignored issues
show
The property exists does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
65
            $this->queuedTags = $tags;
66
67
            return;
68
        }
69
70
        $this->attachTags($tags);
71
    }
72
73
    /**
74
     * @param \Illuminate\Database\Eloquent\Builder $query
75
     * @param array|\ArrayAccess|\Spatie\Tags\Tag $tags
76
     *
77
     * @return \Illuminate\Database\Eloquent\Builder
78
     */
79
    public function scopeWithAllTags(Builder $query, $tags, string $type = null): Builder
80
    {
81
        $tags = static::convertToTags($tags, $type);
82
83
        collect($tags)->each(function ($tag) use ($query) {
84
            $query->whereHas('tags', function (Builder $query) use ($tag) {
85
                $query->where('tags.id', $tag ? $tag->id : 0);
86
            });
87
        });
88
89
        return $query;
90
    }
91
92
    /**
93
     * @param \Illuminate\Database\Eloquent\Builder $query
94
     * @param array|\ArrayAccess|\Spatie\Tags\Tag $tags
95
     *
96
     * @return \Illuminate\Database\Eloquent\Builder
97
     */
98 View Code Duplication
    public function scopeWithAnyTags(Builder $query, $tags, string $type = null): Builder
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
99
    {
100
        $tags = static::convertToTags($tags, $type);
101
102
        return $query->whereHas('tags', function (Builder $query) use ($tags) {
103
            $tagIds = collect($tags)->pluck('id');
104
105
            $query->whereIn('tags.id', $tagIds);
106
        });
107
    }
108
109 View Code Duplication
    public function scopeWithAllTagsOfAnyType(Builder $query, $tags): Builder
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
110
    {
111
        $tags = static::convertToTagsOfAnyType($tags);
112
113
        collect($tags)->each(function ($tag) use ($query) {
114
            $query->whereHas('tags', function (Builder $query) use ($tag) {
115
                $query->where('tags.id', $tag ? $tag->id : 0);
116
            });
117
        });
118
119
        return $query;
120
    }
121
122 View Code Duplication
    public function scopeWithAnyTagsOfAnyType(Builder $query, $tags): Builder
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
123
    {
124
        $tags = static::convertToTagsOfAnyType($tags);
125
126
        return $query->whereHas('tags', function (Builder $query) use ($tags) {
127
            $tagIds = collect($tags)->pluck('id');
128
129
            $query->whereIn('tags.id', $tagIds);
130
        });
131
    }
132
133
    public function tagsWithType(string $type = null): Collection
134
    {
135
        return $this->tags->filter(function (Tag $tag) use ($type) {
0 ignored issues
show
The property tags does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
136
            return $tag->type === $type;
137
        });
138
    }
139
140
    /**
141
     * @param array|\ArrayAccess|\Spatie\Tags\Tag $tags
142
     *
143
     * @return $this
144
     */
145 View Code Duplication
    public function attachTags($tags)
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
146
    {
147
        $className = static::getTagClassName();
148
149
        $tags = collect($className::findOrCreate($tags));
150
151
        $this->tags()->syncWithoutDetaching($tags->pluck('id')->toArray());
152
153
        return $this;
154
    }
155
156
    /**
157
     * @param string|\Spatie\Tags\Tag $tag
158
     *
159
     * @return $this
160
     */
161
    public function attachTag($tag)
162
    {
163
        return $this->attachTags([$tag]);
164
    }
165
166
    /**
167
     * @param array|\ArrayAccess $tags
168
     *
169
     * @return $this
170
     */
171
    public function detachTags($tags)
172
    {
173
        $tags = static::convertToTags($tags);
174
175
        collect($tags)
176
            ->filter()
177
            ->each(function (Tag $tag) {
178
                $this->tags()->detach($tag);
179
            });
180
181
        return $this;
182
    }
183
184
    /**
185
     * @param string|\Spatie\Tags\Tag $tag
186
     *
187
     * @return $this
188
     */
189
    public function detachTag($tag)
190
    {
191
        return $this->detachTags([$tag]);
192
    }
193
194
    /**
195
     * @param array|\ArrayAccess $tags
196
     *
197
     * @return $this
198
     */
199 View Code Duplication
    public function syncTags($tags)
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
200
    {
201
        $className = static::getTagClassName();
202
203
        $tags = collect($className::findOrCreate($tags));
204
205
        $this->tags()->sync($tags->pluck('id')->toArray());
206
207
        return $this;
208
    }
209
210
    /**
211
     * @param array|\ArrayAccess $tags
212
     * @param string|null $type
213
     *
214
     * @return $this
215
     */
216 View Code Duplication
    public function syncTagsWithType($tags, string $type = null)
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
217
    {
218
        $className = static::getTagClassName();
219
220
        $tags = collect($className::findOrCreate($tags, $type));
221
222
        $this->syncTagIds($tags->pluck('id')->toArray(), $type);
223
224
        return $this;
225
    }
226
227
    protected static function convertToTags($values, $type = null, $locale = null)
228
    {
229
        return collect($values)->map(function ($value) use ($type, $locale) {
230
            if ($value instanceof Tag) {
231
                if (isset($type) && $value->type != $type) {
232
                    throw new InvalidArgumentException("Type was set to {$type} but tag is of type {$value->type}");
233
                }
234
235
                return $value;
236
            }
237
238
            $className = static::getTagClassName();
239
240
            return $className::findFromString($value, $type, $locale);
241
        });
242
    }
243
244
    protected static function convertToTagsOfAnyType($values, $locale = null)
245
    {
246
        return collect($values)->map(function ($value) use ($locale) {
247
            if ($value instanceof Tag) {
248
                return $value;
249
            }
250
251
            $className = static::getTagClassName();
252
253
            return $className::findFromStringOfAnyType($value, $locale);
254
        });
255
    }
256
257
    /**
258
     * Use in place of eloquent's sync() method so that the tag type may be optionally specified.
259
     *
260
     * @param $ids
261
     * @param string|null $type
262
     * @param bool $detaching
263
     */
264
    protected function syncTagIds($ids, string $type = null, $detaching = true)
265
    {
266
        $isUpdated = false;
267
268
        // Get a list of tag_ids for all current tags
269
        $current = $this->tags()
270
            ->newPivotStatement()
271
            ->where('taggable_id', $this->getKey())
0 ignored issues
show
It seems like getKey() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
272
            ->where('taggable_type', $this->getMorphClass())
0 ignored issues
show
It seems like getMorphClass() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
273
            ->when($type !== null, function ($query) use ($type) {
274
                $tagModel = $this->tags()->getRelated();
275
276
                return $query->join(
277
                    $tagModel->getTable(),
278
                    'taggables.tag_id',
279
                    '=',
280
                    $tagModel->getTable().'.'.$tagModel->getKeyName()
281
                )
282
                    ->where('tags.type', $type);
283
            })
284
            ->pluck('tag_id')
285
            ->all();
286
287
        // Compare to the list of ids given to find the tags to remove
288
        $detach = array_diff($current, $ids);
289
        if ($detaching && count($detach) > 0) {
290
            $this->tags()->detach($detach);
291
            $isUpdated = true;
292
        }
293
294
        // Attach any new ids
295
        $attach = array_diff($ids, $current);
296
        if (count($attach) > 0) {
297
            collect($attach)->each(function ($id) {
298
                $this->tags()->attach($id, []);
299
            });
300
            $isUpdated = true;
301
        }
302
303
        // Once we have finished attaching or detaching the records, we will see if we
304
        // have done any attaching or detaching, and if we have we will touch these
305
        // relationships if they are configured to touch on any database updates.
306
        if ($isUpdated) {
307
            $this->tags()->touchIfTouching();
308
        }
309
    }
310
}
311