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

HasStatuses::scopeCurrentStatusDateBetween()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 9.568
c 0
b 0
f 0
cc 1
nc 1
nop 3
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)
100
    {
101
        $builder
102
            ->whereHas(
103
                'statuses',
104
                function (Builder $query) use ($startDate, $endDate) {
105
                    $query
106
                        ->where('created_at', '>=', $startDate->format('Y-m-d 00:00'))
107
                        ->where('created_at', '<=', $endDate->format('Y-m-d 23:59'))
108
                        ->whereIn(
109
                            'id',
110
                            function (QueryBuilder $query) {
111
                                $query
112
                                    ->select(DB::raw('max(id)'))
113
                                    ->from($this->getStatusTableName())
114
                                    ->where('model_type', $this->getStatusModelType())
115
                                    ->groupBy($this->getModelKeyColumnName());
116
                            }
117
                        );
118
                }
119
            );
120
    }
121
122
    /**
123
     * @param string|array $names
124
     *
125
     * @return void
126
     **/
127
    public function scopeOtherCurrentStatus(Builder $builder, ...$names)
128
    {
129
        $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...
130
        $builder
131
            ->whereHas(
132
                'statuses',
133
                function (Builder $query) use ($names) {
134
                    $query
135
                        ->whereNotIn('name', $names)
136
                        ->whereIn(
137
                            'id',
138
                            function (QueryBuilder $query) use ($names) {
139
                                $query
140
                                    ->select(DB::raw('max(id)'))
141
                                    ->from($this->getStatusTableName())
142
                                    ->where('model_type', $this->getStatusModelType())
143
                                    ->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...
144
                            }
145
                        );
146
                }
147
            )
148
            ->orWhereDoesntHave('statuses');
149
    }
150
151
    public function getStatusAttribute(): string
152
    {
153
        return (string) $this->latestStatus();
154
    }
155
156
    public function forceSetStatus(string $name, ?string $reason = null): self
157
    {
158
        $oldStatus = $this->latestStatus();
159
160
        $newStatus = $this->statuses()->create([
161
            'name'   => $name,
162
            'reason' => $reason,
163
        ]);
164
165
        event(new StatusUpdated($oldStatus, $newStatus, $this));
166
167
        return $this;
168
    }
169
170
    protected function getStatusTableName(): string
171
    {
172
        $modelClass = $this->getStatusModelClassName();
173
174
        return (new $modelClass)->getTable();
175
    }
176
177
    protected function getModelKeyColumnName(): string
178
    {
179
        return config('model-status.model_primary_key_attribute') ?? 'model_id';
180
    }
181
182
    protected function getStatusModelClassName(): string
183
    {
184
        return config('model-status.status_model');
185
    }
186
187
    protected function getStatusModelType(): string
188
    {
189
        return array_search(static::class, Relation::morphMap()) ?: static::class;
190
    }
191
}
192