Completed
Push — master ( 79ff7a...fed05a )
by Freek
10s
created

HasStatuses::getStatusModelType()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 2
eloc 2
nc 2
nop 0
1
<?php
2
3
namespace Spatie\ModelStatus;
4
5
use Illuminate\Support\Facades\DB;
6
use Illuminate\Database\Eloquent\Builder;
7
use Spatie\ModelStatus\Events\StatusUpdated;
8
use Spatie\ModelStatus\Exceptions\InvalidStatus;
9
use Illuminate\Database\Eloquent\Relations\Relation;
10
use Illuminate\Database\Eloquent\Relations\MorphMany;
11
use Illuminate\Database\Query\Builder as QueryBuilder;
12
13
trait HasStatuses
14
{
15
    public function statuses(): MorphMany
16
    {
17
        return $this->morphMany($this->getStatusModelClassName(), 'model')->latest('id');
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...
18
    }
19
20
    public function status(): ?Status
21
    {
22
        return $this->latestStatus();
23
    }
24
25
    public function setStatus(string $name, string $reason = ''): self
26
    {
27
        if (! $this->isValidStatus($name, $reason)) {
28
            throw InvalidStatus::create($name);
29
        }
30
31
        return $this->forceSetStatus($name, $reason);
32
    }
33
34
    public function isValidStatus(string $name, string $reason = ''): 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...
35
    {
36
        return true;
37
    }
38
39
    /**
40
     * @param string|array $names
41
     *
42
     * @return null|Status
43
     */
44
    public function latestStatus(...$names): ?Status
45
    {
46
        $names = is_array($names) ? array_flatten($names) : func_get_args();
47
48
        $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...
49
50
        if (count($names) < 1) {
51
            return $statuses->first();
52
        }
53
54
        return $statuses->whereIn('name', $names)->first();
55
    }
56
57
    public function scopeCurrentStatus(Builder $builder, ...$names)
58
    {
59
        $names = is_array($names) ? array_flatten($names) : func_get_args();
60
        $builder
61
            ->whereHas('statuses',
62
                function (Builder $query) use ($names) {
63
                    $query
64
                        ->whereIn('name', $names)
65
                        ->whereIn('id',
66
                            function (QueryBuilder $query) {
67
                                $query
68
                                    ->select(DB::raw('max(id)'))
69
                                    ->from($this->getStatusTableName())
70
                                    ->where('model_type', $this->getStatusModelType())
71
                                    ->groupBy('model_id');
72
                            });
73
                });
74
    }
75
76
    /**
77
     * @param string|array $names
78
     *
79
     * @return void
80
     **/
81
    public function scopeOtherCurrentStatus(Builder $builder, ...$names)
82
    {
83
        $names = is_array($names) ? array_flatten($names) : func_get_args();
84
        $builder
85
            ->whereHas('statuses',
86
                function (Builder $query) use ($names) {
87
                    $query
88
                        ->whereNotIn('name', $names)
89
                        ->whereIn('id',
90
                            function (QueryBuilder $query) use ($names) {
91
                                $query
92
                                    ->select(DB::raw('max(id)'))
93
                                    ->from($this->getStatusTableName())
94
                                    ->where('model_type', $this->getStatusModelType())
95
                                    ->groupBy('model_id');
96
                            });
97
                })
98
            ->orWhereDoesntHave('statuses');
99
    }
100
101
    public function getStatusAttribute(): string
102
    {
103
        return (string) $this->latestStatus();
104
    }
105
106
    public function forceSetStatus(string $name, string $reason = ''): self
107
    {
108
        $oldStatus = $this->latestStatus();
109
110
        $newStatus = $this->statuses()->create([
111
            'name' => $name,
112
            'reason' => $reason,
113
        ]);
114
115
        event(new StatusUpdated($oldStatus, $newStatus, $this));
116
117
        return $this;
118
    }
119
120
    protected function getStatusTableName(): string
121
    {
122
        $modelClass = $this->getStatusModelClassName();
123
124
        return (new $modelClass)->getTable();
125
    }
126
127
    protected function getStatusModelClassName(): string
128
    {
129
        return config('model-status.status_model');
130
    }
131
132
    protected function getStatusModelType(): string
133
    {
134
        return array_search(static::class, Relation::morphMap()) ?: static::class;
135
    }
136
}
137