Completed
Push — master ( cfc1cd...1f5aff )
by Freek
16:04
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
    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->table}.{$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
    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('id', $tagIds);
91
        });
92
    }
93
94
    public function tagsWithType(string $type = null): Collection
95
    {
96
        return $this->tags->filter(function (Tag $tag) use ($type) {
97
            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...
98
        });
99
    }
100
101
    /**
102
     * @param array|\ArrayAccess|\Spatie\Tags\Tag $tags
103
     *
104
     * @return $this
105
     */
106 View Code Duplication
    public function attachTags($tags)
107
    {
108
        $className = static::getTagClassName();
109
110
        $tags = collect($className::findOrCreate($tags));
111
112
        $this->tags()->syncWithoutDetaching($tags->pluck('id')->toArray());
113
114
        return $this;
115
    }
116
117
    /**
118
     * @param string|\Spatie\Tags\Tag $tag
119
     *
120
     * @return $this
121
     */
122
    public function attachTag($tag)
123
    {
124
        return $this->attachTags([$tag]);
125
    }
126
127
    /**
128
     * @param array|\ArrayAccess $tags
129
     *
130
     * @return $this
131
     */
132
    public function detachTags($tags)
133
    {
134
        $tags = static::convertToTags($tags);
135
136
        collect($tags)
137
            ->filter()
138
            ->each(function (Tag $tag) {
139
                $this->tags()->detach($tag);
140
            });
141
142
        return $this;
143
    }
144
145
    /**
146
     * @param string|\Spatie\Tags\Tag $tag
147
     *
148
     * @return $this
149
     */
150
    public function detachTag($tag)
151
    {
152
        return $this->detachTags([$tag]);
153
    }
154
155
    /**
156
     * @param array|\ArrayAccess $tags
157
     *
158
     * @return $this
159
     */
160 View Code Duplication
    public function syncTags($tags)
161
    {
162
        $className = static::getTagClassName();
163
164
        $tags = collect($className::findOrCreate($tags));
165
166
        $this->tags()->sync($tags->pluck('id')->toArray());
167
168
        return $this;
169
    }
170
171
    /**
172
     * @param array|\ArrayAccess $tags
173
     * @param string|null $type
174
     *
175
     * @return $this
176
     */
177 View Code Duplication
    public function syncTagsWithType($tags, string $type = null)
178
    {
179
        $className = static::getTagClassName();
180
181
        $tags = collect($className::findOrCreate($tags, $type));
182
183
        $this->syncTagIds($tags->pluck('id')->toArray(), $type);
184
185
        return $this;
186
    }
187
188
    protected static function convertToTags($values, $type = null, $locale = null)
189
    {
190
        return collect($values)->map(function ($value) use ($type, $locale) {
191
            if ($value instanceof Tag) {
192
                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...
193
                    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...
194
                }
195
196
                return $value;
197
            }
198
199
            $className = static::getTagClassName();
200
201
            return $className::findFromString($value, $type, $locale);
202
        });
203
    }
204
205
    /**
206
     * Use in place of eloquent's sync() method so that the tag type may be optionally specified.
207
     *
208
     * @param $ids
209
     * @param string|null $type
210
     * @param bool $detaching
211
     */
212
    protected function syncTagIds($ids, string $type = null, $detaching = true)
213
    {
214
        $isUpdated = false;
215
216
        // Get a list of tag_ids for all current tags
217
        $current = $this->tags()
218
            ->newPivotStatement()
219
            ->where('taggable_id', $this->getKey())
220
            ->when($type !== null, function ($query) use ($type) {
221
                $tagModel = $this->tags()->getRelated();
222
223
                return $query->join(
224
                    $tagModel->getTable(),
225
                    'taggables.tag_id',
226
                    '=',
227
                    $tagModel->getTable().'.'.$tagModel->getKeyName()
228
                )
229
                    ->where('tags.type', $type);
230
            })
231
            ->pluck('tag_id')
232
            ->all();
233
234
        // Compare to the list of ids given to find the tags to remove
235
        $detach = array_diff($current, $ids);
236
        if ($detaching && count($detach) > 0) {
237
            $this->tags()->detach($detach);
238
            $isUpdated = true;
239
        }
240
241
        // Attach any new ids
242
        $attach = array_diff($ids, $current);
243
        if (count($attach) > 0) {
244
            collect($attach)->each(function ($id) {
245
                $this->tags()->attach($id, []);
246
            });
247
            $isUpdated = true;
248
        }
249
250
        // Once we have finished attaching or detaching the records, we will see if we
251
        // have done any attaching or detaching, and if we have we will touch these
252
        // relationships if they are configured to touch on any database updates.
253
        if ($isUpdated) {
254
            $this->tags()->touchIfTouching();
255
        }
256
    }
257
}
258