Completed
Push — master ( 57bebd...1f754e )
by Freek
10s
created

HasStatuses::getModelKeyColumnName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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