Completed
Push — master ( 497186...38c187 )
by Freek
02:38
created

HasTags::convertToTags()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 1
nop 3
1
<?php
2
3
namespace Spatie\Tags;
4
5
use Illuminate\Database\Eloquent\Builder;
6
use Illuminate\Database\Eloquent\Collection;
7
use Illuminate\Database\Eloquent\Model;
8
use Illuminate\Database\Eloquent\Relations\MorphToMany;
9
10
trait HasTags
11
{
12
    protected $queuedTags = [];
13
14
    public static function bootHasTags()
15
    {
16
        static::created(function (Model $taggableModel) {
17
            $taggableModel->attachTags($taggableModel->queuedTags);
18
19
            $taggableModel->queuedTags = [];
20
        });
21
    }
22
23
    public function tags(): MorphToMany
24
    {
25
        return $this
0 ignored issues
show
Bug introduced by
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...
26
            ->morphToMany(Tag::class, 'taggable')
27
            ->orderBy('order_column');
28
    }
29
30
    /**
31
     * @param string|array|\ArrayAccess|\Spatie\Tags\Tags $tags
32
     */
33
    public function setTagsAttribute($tags)
34
    {
35
        if (! $this->exists) {
0 ignored issues
show
Bug introduced by
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...
36
            $this->queuedTags = $tags;
37
38
            return;
39
        }
40
41
        $this->attachTags($tags);
42
    }
43
44
    /**
45
     * @param \Illuminate\Database\Eloquent\Builder $query
46
     * @param array|\ArrayAccess|\Spatie\Tags\Tags $tags
47
     *
48
     * @return \Illuminate\Database\Eloquent\Builder
49
     */
50 View Code Duplication
    public function scopeWithAllTags(Builder $query, $tags): Builder
0 ignored issues
show
Duplication introduced by
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...
51
    {
52
        $tags = static::convertToTags($tags);
53
54
        collect($tags)->each(function ($tag) use ($query) {
55
            $query->whereHas('tags', function (Builder $query) use ($tag) {
56
                return $query->where('id', $tag ? $tag->id : 0);
57
            });
58
        });
59
60
        return $query;
61
    }
62
63
    /**
64
     * @param \Illuminate\Database\Eloquent\Builder $query
65
     * @param array|\ArrayAccess|\Spatie\Tags\Tags $tags
66
     *
67
     * @return \Illuminate\Database\Eloquent\Builder
68
     */
69 View Code Duplication
    public function scopeWithAnyTags(Builder $query, $tags): Builder
0 ignored issues
show
Duplication introduced by
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...
70
    {
71
        $tags = static::convertToTags($tags);
72
73
        return $query->whereHas('tags', function (Builder $query) use ($tags) {
74
            $tagIds = collect($tags)->map(function ($tag) {
75
                return $tag ? $tag->id : 0;
76
            })->toArray();
77
78
            $query->whereIn('id', $tagIds);
79
        });
80
    }
81
82
83
    public function tagsWithType(string $type = null): Collection
84
    {
85
        return $this->tags->filter(function (Tag $tag) use ($type) {
0 ignored issues
show
Bug introduced by
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...
86
            return $tag->type === $type;
87
        });
88
    }
89
90
    /**
91
     * @param array|\ArrayAccess|\Spatie\Tags\Tag $tags
92
     *
93
     * @return $this
94
     */
95
    public function attachTags($tags)
96
    {
97
        if (! count($tags)) {
98
            return $this;
99
        }
100
101
        $tags = Tag::findOrCreate($tags);
102
103
        collect($tags)->each(function (Tag $tag) {
104
            $this->tags()->attach($tag);
105
        });
106
107
        return $this;
108
    }
109
110
    /**
111
     * @param string|\Spatie\Tags\Tag $tag
112
     *
113
     * @return $this
114
     */
115
    public function attachTag($tag)
116
    {
117
        return $this->attachTags([$tag]);
118
    }
119
120
    /**
121
     * @param array|\ArrayAccess|\Spatie\Tags\Tag $tags
122
     *
123
     * @return $this
124
     */
125
    public function detachTags($tags)
126
    {
127
        if (! is_array($tags)) {
128
            $tags = [$tags];
129
        }
130
131
        $tags = static::convertToTags($tags);
132
133
        collect($tags)
134
            ->filter()
135
            ->each(function (Tag $tag) {
136
                $this->tags()->detach($tag);
137
            });
138
139
        return $this;
140
    }
141
142
    /**
143
     * @param array|\ArrayAccess|\Spatie\Tags\Tag $tags
144
     *
145
     * @return $this
146
     */
147
    public function detachTag($tags)
148
    {
149
        return $this->detachTags($tags);
150
    }
151
152
    /**
153
     * @param array|\ArrayAccess $tags
154
     *
155
     * @return $this
156
     */
157
    public function syncTags($tags)
158
    {
159
        $tags = Tag::findOrCreate($tags);
160
161
        if (! $tags instanceof \Illuminate\Support\Collection) {
162
            $tags = collect($tags);
163
        }
164
165
        $this->tags()->sync($tags->pluck('id')->toArray());
0 ignored issues
show
Bug introduced by
The method pluck does only exist in Illuminate\Support\Collection, but not in Spatie\Tags\Tag.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
166
167
168
        return $this;
169
    }
170
171
    protected static function convertToTags($values, $type = null, $locale = null)
172
    {
173
        return collect($values)->map(function (string $value) use ($type, $locale) {
174
            if ($value instanceof Tag) {
175
                return $value;
176
            }
177
178
            return Tag::findFromString($value, $type, $locale);
179
        });
180
    }
181
182
}
183