Completed
Push — 2.4 ( d8c2c9...35279c )
by James
98:56 queued 97:01
created

HasTags::syncTags()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 8
Ratio 100 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 8
loc 8
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of Cachet.
5
 *
6
 * (c) Alt Three Services Limited
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace CachetHQ\Cachet\Models\Traits;
13
14
use CachetHQ\Cachet\Models\Tag;
15
use Illuminate\Database\Eloquent\Builder;
16
use Illuminate\Database\Eloquent\Model;
17
18
/**
19
 * This is the has tags trait.
20
 * Code based on https://github.com/spatie/laravel-tags.
21
 *
22
 * @author James Brooks <[email protected]>
23
 */
24
trait HasTags
25
{
26
    /**
27
     * @var array
28
     */
29
    protected $queuedTags = [];
30
31
    /**
32
     * Boot the trait.
33
     *
34
     * @return void
35
     */
36 126
    public static function bootHasTags()
37
    {
38
        static::created(function (Model $taggableModel) {
39 43
            if (count($taggableModel->queuedTags) > 0) {
40
                $taggableModel->attachTags($taggableModel->queuedTags);
41
42
                $taggableModel->queuedTags = [];
43
            }
44 126
        });
45
46
        static::deleted(function (Model $deletedModel) {
47 2
            $tags = $deletedModel->tags()->get();
48
49 2
            $deletedModel->detachTags($tags);
50 126
        });
51
    }
52
53
    /**
54
     * Get the tags relation.
55
     *
56
     * @return \Illuminate\Database\Eloquent\Relations\MorphToMany
57
     */
58 16
    public function tags()
59
    {
60 16
        return $this->morphToMany(Tag::class, 'taggable');
0 ignored issues
show
Bug introduced by James Brooks
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...
61
    }
62
63
    /**
64
     * @param string|array|\ArrayAccess|\CachetHQ\Cachet\Models\Tag $tags
65
     */
66
    public function setTagsAttribute($tags)
67
    {
68
        if (!$this->exists) {
0 ignored issues
show
Bug introduced by James Brooks
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...
69
            $this->queuedTags = $tags;
0 ignored issues
show
Documentation Bug introduced by James Brooks
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...
70
71
            return;
72
        }
73
74
        $this->attachTags($tags);
75
    }
76
77
    /**
78
     * @param \Illuminate\Database\Eloquent\Builder $query
79
     * @param array|\ArrayAccess                    $tags
80
     *
81
     * @return \Illuminate\Database\Eloquent\Builder
82
     */
83 View Code Duplication
    public function scopeWithAllTags(Builder $query, $tags)
84
    {
85
        $tags = static::convertToTags($tags);
86
87
        $tags->each(function ($tag) use ($query) {
88
            $query->whereHas('tags', function (Builder $query) use ($tag) {
89
                return $query->where('tags.id', $tag ? $tag->id : 0);
90
            });
91
        });
92
93
        return $query;
94
    }
95
96
    /**
97
     * @param \Illuminate\Database\Eloquent\Builder $query
98
     * @param array|\ArrayAccess                    $tags
99
     *
100
     * @return \Illuminate\Database\Eloquent\Builder
101
     */
102 1 View Code Duplication
    public function scopeWithAnyTags(Builder $query, $tags)
103
    {
104 1
        $tags = static::convertToTags($tags);
105
106
        return $query->whereHas('tags', function (Builder $query) use ($tags) {
107 1
            $tagIds = collect($tags)->pluck('id');
108
109 1
            $query->whereIn('tags.id', $tagIds);
110 1
        });
111
    }
112
113
    /**
114
     * @param array|\ArrayAccess|\CachetHQ\Cachet\Models\Tag $tags
115
     *
116
     * @return $this
117
     */
118 2 View Code Duplication
    public function attachTags($tags)
119
    {
120 2
        $tags = collect(Tag::findOrCreate($tags));
121
122 2
        $this->tags()->syncWithoutDetaching($tags->pluck('id')->toArray());
123
124 2
        return $this;
125
    }
126
127
    /**
128
     * @param string|\CachetHQ\Cachet\Models\Tag $tag
129
     *
130
     * @return $this
131
     */
132
    public function attachTag($tag)
133
    {
134
        return $this->attachTags([$tag]);
135
    }
136
137
    /**
138
     * @param array|\ArrayAccess $tags
139
     *
140
     * @return $this
141
     */
142 2
    public function detachTags($tags)
143
    {
144 2
        $tags = static::convertToTags($tags);
145
146 2
        collect($tags)
147 2
            ->filter()
148
            ->each(function (Tag $tag) {
149
                $this->tags()->detach($tag);
150 2
            });
151
152 2
        return $this;
153
    }
154
155
    /**
156
     * @param string|\CachetHQ\Cachet\Models\Tag $tag
157
     *
158
     * @return $this
159
     */
160
    public function detachTag($tag)
161
    {
162
        return $this->detachTags([$tag]);
163
    }
164
165
    /**
166
     * @param array|\ArrayAccess $tags
167
     *
168
     * @return $this
169
     */
170 1 View Code Duplication
    public function syncTags($tags)
171
    {
172 1
        $tags = collect(Tag::findOrCreate($tags));
173
174 1
        $this->tags()->sync($tags->pluck('id')->toArray());
175
176 1
        return $this;
177
    }
178
179
    /**
180
     * Convert a list of tags into a collection of \CachetHQ\Cachet\Models\Tag.
181
     *
182
     * @param array|\ArrayAccess $values
183
     *
184
     * @return \Illuminate\Support\Collection
185
     */
186 3
    protected static function convertToTags($values)
187
    {
188
        return collect($values)->map(function ($value) {
189 1
            if ($value instanceof Tag) {
190
                return $value;
191
            }
192
193 1
            return Tag::where('slug', '=', $value)->first();
194 3
        });
195
    }
196
}
197