Completed
Pull Request — master (#68)
by
unknown
01:11
created

HasStatuses::scopeCurrentStatusDateBetween()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 9.536
c 0
b 0
f 0
cc 2
nc 2
nop 4
1
<?php
2
3
namespace Spatie\ModelStatus;
4
5
use Carbon\Carbon;
6
use Illuminate\Database\Eloquent\Builder;
7
use Illuminate\Database\Eloquent\Relations\MorphMany;
8
use Illuminate\Database\Eloquent\Relations\Relation;
9
use Illuminate\Database\Query\Builder as QueryBuilder;
10
use Illuminate\Support\Arr;
11
use Illuminate\Support\Facades\DB;
12
use Spatie\ModelStatus\Events\StatusUpdated;
13
use Spatie\ModelStatus\Exceptions\InvalidStatus;
14
15
trait HasStatuses
16
{
17
    public function statuses(): MorphMany
18
    {
19
        return $this->morphMany($this->getStatusModelClassName(), 'model', 'model_type', $this->getModelKeyColumnName())
0 ignored issues
show
Bug introduced by
It seems like morphMany() 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...
20
            ->latest('id');
21
    }
22
23
    public function status(): ?Status
24
    {
25
        return $this->latestStatus();
26
    }
27
28
    public function setStatus(string $name, ?string $reason = null): self
29
    {
30
        if (! $this->isValidStatus($name, $reason)) {
31
            throw InvalidStatus::create($name);
32
        }
33
34
        return $this->forceSetStatus($name, $reason);
35
    }
36
37
    public function isValidStatus(string $name, ?string $reason = null): bool
0 ignored issues
show
Unused Code introduced by
The parameter $name is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $reason is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
38
    {
39
        return true;
40
    }
41
42
    /**
43
     * @param string|array $names
44
     *
45
     * @return null|Status
46
     */
47
    public function latestStatus(...$names): ?Status
48
    {
49
        $statuses = $this->relationLoaded('statuses') ? $this->statuses : $this->statuses();
0 ignored issues
show
Bug introduced by
The property statuses 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...
Bug introduced by
It seems like relationLoaded() 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...
50
51
        $names = is_array($names) ? Arr::flatten($names) : func_get_args();
0 ignored issues
show
Documentation introduced by
$names is of type array, but the function expects a object<Illuminate\Support\iterable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
52
        if (count($names) < 1) {
53
            return $statuses->first();
54
        }
55
56
        return $statuses->whereIn('name', $names)->first();
57
    }
58
59
    public function hasEverHadStatus($name): bool
60
    {
61
        $statuses = $this->relationLoaded('statuses') ? $this->statuses : $this->statuses();
0 ignored issues
show
Bug introduced by
It seems like relationLoaded() 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...
62
63
        return $statuses->where('name', $name)->count() > 0;
64
    }
65
66
    public function deleteStatus(...$names)
67
    {
68
        $names = is_array($names) ? Arr::flatten($names) : func_get_args();
0 ignored issues
show
Documentation introduced by
$names is of type array, but the function expects a object<Illuminate\Support\iterable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
69
        if (count($names) < 1) {
70
            return $this;
71
        }
72
73
        $this->statuses()->whereIn('name', $names)->delete();
0 ignored issues
show
Bug introduced by
The method whereIn() does not exist on Illuminate\Database\Eloquent\Relations\MorphMany. Did you maybe mean whereInMethod()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
74
    }
75
76
    public function scopeCurrentStatus(Builder $builder, ...$names)
77
    {
78
        $names = is_array($names) ? Arr::flatten($names) : func_get_args();
0 ignored issues
show
Documentation introduced by
$names is of type array, but the function expects a object<Illuminate\Support\iterable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
79
        $builder
80
            ->whereHas(
81
                'statuses',
82
                function (Builder $query) use ($names) {
83
                    $query
84
                        ->whereIn('name', $names)
85
                        ->whereIn(
86
                            'id',
87
                            function (QueryBuilder $query) {
88
                                $query
89
                                    ->select(DB::raw('max(id)'))
90
                                    ->from($this->getStatusTableName())
91
                                    ->where('model_type', $this->getStatusModelType())
92
                                    ->whereColumn($this->getModelKeyColumnName(), $this->getQualifiedKeyName());
0 ignored issues
show
Bug introduced by
It seems like getQualifiedKeyName() 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...
93
                            }
94
                        );
95
                }
96
            );
97
    }
98
99
    public function scopeCurrentStatusDateBetween(Builder $builder, Carbon $startDate, Carbon $endDate, ...$names)
100
    {
101
        $names = is_array($names) ? Arr::flatten($names) : func_get_args();
0 ignored issues
show
Documentation introduced by
$names is of type array, but the function expects a object<Illuminate\Support\iterable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
102
        $builder
103
            ->whereHas(
104
                'statuses',
105
                function (Builder $query) use ($startDate, $endDate, $names) {
106
                    $query
107
                        ->whereIn('name', $names)
108
                        ->where('created_at', '>=', $startDate->format('Y-m-d 00:00'))
109
                        ->where('created_at', '<=', $endDate->format('Y-m-d 23:59'))
110
                        ->whereIn(
111
                            'id',
112
                            function (QueryBuilder $query) {
113
                                $query
114
                                    ->select(DB::raw('max(id)'))
115
                                    ->from($this->getStatusTableName())
116
                                    ->where('model_type', $this->getStatusModelType())
117
                                    ->groupBy($this->getModelKeyColumnName());
118
                            }
119
                        );
120
                }
121
            );
122
    }
123
124
    /**
125
     * @param string|array $names
126
     *
127
     * @return void
128
     **/
129
    public function scopeOtherCurrentStatus(Builder $builder, ...$names)
130
    {
131
        $names = is_array($names) ? Arr::flatten($names) : func_get_args();
0 ignored issues
show
Documentation introduced by
$names is of type array, but the function expects a object<Illuminate\Support\iterable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
132
        $builder
133
            ->whereHas(
134
                'statuses',
135
                function (Builder $query) use ($names) {
136
                    $query
137
                        ->whereNotIn('name', $names)
138
                        ->whereIn(
139
                            'id',
140
                            function (QueryBuilder $query) use ($names) {
141
                                $query
142
                                    ->select(DB::raw('max(id)'))
143
                                    ->from($this->getStatusTableName())
144
                                    ->where('model_type', $this->getStatusModelType())
145
                                    ->whereColumn($this->getModelKeyColumnName(), $this->getQualifiedKeyName());
0 ignored issues
show
Bug introduced by
It seems like getQualifiedKeyName() 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...
146
                            }
147
                        );
148
                }
149
            )
150
            ->orWhereDoesntHave('statuses');
151
    }
152
153
    public function getStatusAttribute(): string
154
    {
155
        return (string) $this->latestStatus();
156
    }
157
158
    public function forceSetStatus(string $name, ?string $reason = null): self
159
    {
160
        $oldStatus = $this->latestStatus();
161
162
        $newStatus = $this->statuses()->create([
163
            'name'   => $name,
164
            'reason' => $reason,
165
        ]);
166
167
        event(new StatusUpdated($oldStatus, $newStatus, $this));
168
169
        return $this;
170
    }
171
172
    protected function getStatusTableName(): string
173
    {
174
        $modelClass = $this->getStatusModelClassName();
175
176
        return (new $modelClass)->getTable();
177
    }
178
179
    protected function getModelKeyColumnName(): string
180
    {
181
        return config('model-status.model_primary_key_attribute') ?? 'model_id';
182
    }
183
184
    protected function getStatusModelClassName(): string
185
    {
186
        return config('model-status.status_model');
187
    }
188
189
    protected function getStatusModelType(): string
190
    {
191
        return array_search(static::class, Relation::morphMap()) ?: static::class;
192
    }
193
}
194