Completed
Push — master ( 05f255...c90432 )
by Freek
04:14
created

src/HasTags.php (4 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
            $taggableModel->attachTags($taggableModel->queuedTags);
24
25
            $taggableModel->queuedTags = [];
26
        });
27
28
        static::deleted(function (Model $deletedModel) {
29
            $tags = $deletedModel->tags()->get();
30
31
            $deletedModel->detachTags($tags);
32
        });
33
    }
34
35
    public function tags(): MorphToMany
36
    {
37
        return $this
38
            ->morphToMany(self::getTagClassName(), 'taggable')
39
            ->orderBy('order_column');
40
    }
41
42
    /**
43
     * @param string|array|\ArrayAccess|\Spatie\Tags\Tag $tags
44
     */
45
    public function setTagsAttribute($tags)
46
    {
47
        if (! $this->exists) {
48
            $this->queuedTags = $tags;
0 ignored issues
show
Documentation Bug introduced by
It seems like $tags can also be of type string or object<ArrayAccess>. However, the property $queuedTags is declared as type array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
49
50
            return;
51
        }
52
53
        $this->attachTags($tags);
54
    }
55
56
    /**
57
     * @param \Illuminate\Database\Eloquent\Builder $query
58
     * @param array|\ArrayAccess|\Spatie\Tags\Tag $tags
59
     *
60
     * @return \Illuminate\Database\Eloquent\Builder
61
     */
62 View Code Duplication
    public function scopeWithAllTags(Builder $query, $tags, string $type = null): Builder
63
    {
64
        $tags = static::convertToTags($tags, $type);
65
66
        collect($tags)->each(function ($tag) use ($query) {
67
            $query->whereIn("{$this->getTable()}.{$this->getKeyName()}", function ($query) use ($tag) {
68
                $query->from('taggables')
69
                    ->select('taggables.taggable_id')
70
                    ->where('taggables.tag_id', $tag ? $tag->id : 0);
71
            });
72
        });
73
74
        return $query;
75
    }
76
77
    /**
78
     * @param \Illuminate\Database\Eloquent\Builder $query
79
     * @param array|\ArrayAccess|\Spatie\Tags\Tag $tags
80
     *
81
     * @return \Illuminate\Database\Eloquent\Builder
82
     */
83 View Code Duplication
    public function scopeWithAnyTags(Builder $query, $tags, string $type = null): Builder
84
    {
85
        $tags = static::convertToTags($tags, $type);
86
87
        return $query->whereHas('tags', function (Builder $query) use ($tags) {
88
            $tagIds = collect($tags)->pluck('id');
89
90
            $query->whereIn('tags.id', $tagIds);
91
        });
92
    }
93
94 View Code Duplication
    public function scopeWithAllTagsOfAnyType(Builder $query, $tags): Builder
95
    {
96
        $tags = static::convertToTagsOfAnyType($tags);
97
98
        collect($tags)->each(function ($tag) use ($query) {
99
            $query->whereIn("{$this->getTable()}.{$this->getKeyName()}", function ($query) use ($tag) {
100
                $query->from('taggables')
101
                    ->select('taggables.taggable_id')
102
                    ->where('taggables.tag_id', $tag ? $tag->id : 0);
103
            });
104
        });
105
106
        return $query;
107
    }
108
109 View Code Duplication
    public function scopeWithAnyTagsOfAnyType(Builder $query, $tags): Builder
110
    {
111
        $tags = static::convertToTagsOfAnyType($tags);
112
113
        return $query->whereHas('tags', function (Builder $query) use ($tags) {
114
            $tagIds = collect($tags)->pluck('id');
115
116
            $query->whereIn('tags.id', $tagIds);
117
        });
118
    }
119
120
    public function tagsWithType(string $type = null): Collection
121
    {
122
        return $this->tags->filter(function (Tag $tag) use ($type) {
123
            return $tag->type === $type;
0 ignored issues
show
The property type does not exist on object<Spatie\Tags\Tag>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
124
        });
125
    }
126
127
    /**
128
     * @param array|\ArrayAccess|\Spatie\Tags\Tag $tags
129
     *
130
     * @return $this
131
     */
132 View Code Duplication
    public function attachTags($tags)
133
    {
134
        $className = static::getTagClassName();
135
136
        $tags = collect($className::findOrCreate($tags));
137
138
        $this->tags()->syncWithoutDetaching($tags->pluck('id')->toArray());
139
140
        return $this;
141
    }
142
143
    /**
144
     * @param string|\Spatie\Tags\Tag $tag
145
     *
146
     * @return $this
147
     */
148
    public function attachTag($tag)
149
    {
150
        return $this->attachTags([$tag]);
151
    }
152
153
    /**
154
     * @param array|\ArrayAccess $tags
155
     *
156
     * @return $this
157
     */
158
    public function detachTags($tags)
159
    {
160
        $tags = static::convertToTags($tags);
161
162
        collect($tags)
163
            ->filter()
164
            ->each(function (Tag $tag) {
165
                $this->tags()->detach($tag);
166
            });
167
168
        return $this;
169
    }
170
171
    /**
172
     * @param string|\Spatie\Tags\Tag $tag
173
     *
174
     * @return $this
175
     */
176
    public function detachTag($tag)
177
    {
178
        return $this->detachTags([$tag]);
179
    }
180
181
    /**
182
     * @param array|\ArrayAccess $tags
183
     *
184
     * @return $this
185
     */
186 View Code Duplication
    public function syncTags($tags)
187
    {
188
        $className = static::getTagClassName();
189
190
        $tags = collect($className::findOrCreate($tags));
191
192
        $this->tags()->sync($tags->pluck('id')->toArray());
193
194
        return $this;
195
    }
196
197
    /**
198
     * @param array|\ArrayAccess $tags
199
     * @param string|null $type
200
     *
201
     * @return $this
202
     */
203 View Code Duplication
    public function syncTagsWithType($tags, string $type = null)
204
    {
205
        $className = static::getTagClassName();
206
207
        $tags = collect($className::findOrCreate($tags, $type));
208
209
        $this->syncTagIds($tags->pluck('id')->toArray(), $type);
210
211
        return $this;
212
    }
213
214
    protected static function convertToTags($values, $type = null, $locale = null)
215
    {
216
        return collect($values)->map(function ($value) use ($type, $locale) {
217
            if ($value instanceof Tag) {
218
                if (isset($type) && $value->type != $type) {
0 ignored issues
show
The property type does not exist on object<Spatie\Tags\Tag>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
219
                    throw new InvalidArgumentException("Type was set to {$type} but tag is of type {$value->type}");
0 ignored issues
show
The property type does not exist on object<Spatie\Tags\Tag>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
220
                }
221
222
                return $value;
223
            }
224
225
            $className = static::getTagClassName();
226
227
            return $className::findFromString($value, $type, $locale);
228
        });
229
    }
230
231
    protected static function convertToTagsOfAnyType($values, $locale = null)
232
    {
233
        return collect($values)->map(function ($value) use ($locale) {
234
            if ($value instanceof Tag) {
235
                return $value;
236
            }
237
238
            $className = static::getTagClassName();
239
240
            return $className::findFromStringOfAnyType($value, $locale);
241
        });
242
    }
243
244
    /**
245
     * Use in place of eloquent's sync() method so that the tag type may be optionally specified.
246
     *
247
     * @param $ids
248
     * @param string|null $type
249
     * @param bool $detaching
250
     */
251
    protected function syncTagIds($ids, string $type = null, $detaching = true)
252
    {
253
        $isUpdated = false;
254
255
        // Get a list of tag_ids for all current tags
256
        $current = $this->tags()
257
            ->newPivotStatement()
258
            ->where('taggable_id', $this->getKey())
259
            ->where('taggable_type', $this->getMorphClass())
260
            ->when($type !== null, function ($query) use ($type) {
261
                $tagModel = $this->tags()->getRelated();
262
263
                return $query->join(
264
                    $tagModel->getTable(),
265
                    'taggables.tag_id',
266
                    '=',
267
                    $tagModel->getTable().'.'.$tagModel->getKeyName()
268
                )
269
                    ->where('tags.type', $type);
270
            })
271
            ->pluck('tag_id')
272
            ->all();
273
274
        // Compare to the list of ids given to find the tags to remove
275
        $detach = array_diff($current, $ids);
276
        if ($detaching && count($detach) > 0) {
277
            $this->tags()->detach($detach);
278
            $isUpdated = true;
279
        }
280
281
        // Attach any new ids
282
        $attach = array_diff($ids, $current);
283
        if (count($attach) > 0) {
284
            collect($attach)->each(function ($id) {
285
                $this->tags()->attach($id, []);
286
            });
287
            $isUpdated = true;
288
        }
289
290
        // Once we have finished attaching or detaching the records, we will see if we
291
        // have done any attaching or detaching, and if we have we will touch these
292
        // relationships if they are configured to touch on any database updates.
293
        if ($isUpdated) {
294
            $this->tags()->touchIfTouching();
295
        }
296
    }
297
}
298