Completed
Push — master ( f19e5b...3446d2 )
by Rias
22s queued 11s
created

src/SortableTrait.php (1 issue)

Labels
Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Spatie\EloquentSortable;
4
5
use ArrayAccess;
6
use Illuminate\Database\Eloquent\Builder;
7
use Illuminate\Database\Eloquent\SoftDeletingScope;
8
use InvalidArgumentException;
9
10
trait SortableTrait
11
{
12
    public static function bootSortableTrait()
13
    {
14
        static::creating(function ($model) {
15
            if ($model instanceof Sortable && $model->shouldSortWhenCreating()) {
16
                $model->setHighestOrderNumber();
17
            }
18
        });
19
    }
20
21
    public function setHighestOrderNumber()
22
    {
23
        $orderColumnName = $this->determineOrderColumnName();
24
25
        $this->$orderColumnName = $this->getHighestOrderNumber() + 1;
26
    }
27
28
    public function getHighestOrderNumber(): int
29
    {
30
        return (int) $this->buildSortQuery()->max($this->determineOrderColumnName());
31
    }
32
33
    public function scopeOrdered(Builder $query, string $direction = 'asc')
34
    {
35
        return $query->orderBy($this->determineOrderColumnName(), $direction);
36
    }
37
38
    public static function setNewOrder($ids, int $startOrder = 1, string $primaryKeyColumn = null)
39
    {
40
        if (! is_array($ids) && ! $ids instanceof ArrayAccess) {
41
            throw new InvalidArgumentException('You must pass an array or ArrayAccess object to setNewOrder');
42
        }
43
44
        $model = new static;
45
46
        $orderColumnName = $model->determineOrderColumnName();
47
48
        if (is_null($primaryKeyColumn)) {
49
            $primaryKeyColumn = $model->getKeyName();
50
        }
51
52
        foreach ($ids as $id) {
53
            static::withoutGlobalScope(SoftDeletingScope::class)
54
                ->where($primaryKeyColumn, $id)
55
                ->update([$orderColumnName => $startOrder++]);
56
        }
57
    }
58
59
    public static function setNewOrderByCustomColumn(string $primaryKeyColumn, $ids, int $startOrder = 1)
60
    {
61
        self::setNewOrder($ids, $startOrder, $primaryKeyColumn);
62
    }
63
64
    protected function determineOrderColumnName(): string
65
    {
66
        return $this->sortable['order_column_name'] ?? 'order_column';
67
    }
68
69
    /**
70
     * Determine if the order column should be set when saving a new model instance.
71
     */
72
    public function shouldSortWhenCreating(): bool
73
    {
74
        return $this->sortable['sort_when_creating'] ?? true;
75
    }
76
77 View Code Duplication
    public function moveOrderDown()
78
    {
79
        $orderColumnName = $this->determineOrderColumnName();
80
81
        $swapWithModel = $this->buildSortQuery()->limit(1)
82
            ->ordered()
83
            ->where($orderColumnName, '>', $this->$orderColumnName)
84
            ->first();
85
86
        if (! $swapWithModel) {
87
            return $this;
88
        }
89
90
        return $this->swapOrderWithModel($swapWithModel);
91
    }
92
93 View Code Duplication
    public function moveOrderUp()
94
    {
95
        $orderColumnName = $this->determineOrderColumnName();
96
97
        $swapWithModel = $this->buildSortQuery()->limit(1)
98
            ->ordered('desc')
99
            ->where($orderColumnName, '<', $this->$orderColumnName)
100
            ->first();
101
102
        if (! $swapWithModel) {
103
            return $this;
104
        }
105
106
        return $this->swapOrderWithModel($swapWithModel);
107
    }
108
109
    public function swapOrderWithModel(Sortable $otherModel)
110
    {
111
        $orderColumnName = $this->determineOrderColumnName();
112
113
        $oldOrderOfOtherModel = $otherModel->$orderColumnName;
114
115
        $otherModel->$orderColumnName = $this->$orderColumnName;
116
        $otherModel->save();
117
118
        $this->$orderColumnName = $oldOrderOfOtherModel;
119
        $this->save();
120
121
        return $this;
122
    }
123
124
    public static function swapOrder(Sortable $model, Sortable $otherModel)
125
    {
126
        $model->swapOrderWithModel($otherModel);
127
    }
128
129
    public function moveToStart()
130
    {
131
        $firstModel = $this->buildSortQuery()->limit(1)
132
            ->ordered()
133
            ->first();
134
135
        if ($firstModel->id === $this->id) {
0 ignored issues
show
The property id 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...
136
            return $this;
137
        }
138
139
        $orderColumnName = $this->determineOrderColumnName();
140
141
        $this->$orderColumnName = $firstModel->$orderColumnName;
142
        $this->save();
143
144
        $this->buildSortQuery()->where($this->getKeyName(), '!=', $this->id)->increment($orderColumnName);
145
146
        return $this;
147
    }
148
149
    public function moveToEnd()
150
    {
151
        $maxOrder = $this->getHighestOrderNumber();
152
153
        $orderColumnName = $this->determineOrderColumnName();
154
155
        if ($this->$orderColumnName === $maxOrder) {
156
            return $this;
157
        }
158
159
        $oldOrder = $this->$orderColumnName;
160
161
        $this->$orderColumnName = $maxOrder;
162
        $this->save();
163
164
        $this->buildSortQuery()->where($this->getKeyName(), '!=', $this->id)
165
            ->where($orderColumnName, '>', $oldOrder)
166
            ->decrement($orderColumnName);
167
168
        return $this;
169
    }
170
171
    public function buildSortQuery()
172
    {
173
        return static::query();
174
    }
175
}
176