Completed
Push — master ( 9c7b17...2ce128 )
by Freek
04:25
created

src/SortableTrait.php (2 issues)

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
7
trait SortableTrait
8
{
9
    /**
10
     * Modify the order column value.
11
     */
12
    public function setHighestOrderNumber()
13
    {
14
        $orderColumnName = $this->determineOrderColumnName();
15
        $this->$orderColumnName = $this->getHighestOrderNumber() + 1;
16
    }
17
18
    /**
19
     * Determine the order value for the new record.
20
     *
21
     * @return int
22
     */
23
    public function getHighestOrderNumber()
24
    {
25
        return (int) static::max($this->determineOrderColumnName());
26
    }
27
28
    /**
29
     * Let's be nice and provide an ordered scope.
30
     *
31
     * @param \Illuminate\Database\Eloquent\Builder $query
32
     * @param string                                $direction
33
     *
34
     * @return \Illuminate\Database\Query\Builder
35
     */
36
    public function scopeOrdered(\Illuminate\Database\Eloquent\Builder $query, $direction = 'asc')
37
    {
38
        return $query->orderBy($this->determineOrderColumnName(), $direction);
39
    }
40
41
    /**
42
     * This function reorders the records: the record with the first id in the array
43
     * will get order 1, the record with the second it will get order 2, ...
44
     *
45
     * A starting order number can be optionally supplied (defaults to 1).
46
     *
47
     * @param array $ids
48
     * @param int   $startOrder
49
     *
50
     * @throws SortableException
51
     */
52
    public static function setNewOrder($ids, $startOrder = 1)
53
    {
54
        if (! is_array($ids) && ! $ids instanceof ArrayAccess) {
55
            throw new SortableException('You must pass an array or ArrayAccess object to setNewOrder');
0 ignored issues
show
Deprecated Code introduced by
The class Spatie\EloquentSortable\SortableException has been deprecated with message: This class will be removed in the next major version.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
56
        }
57
58
        $model = new static;
59
60
        $orderColumnName = $model->determineOrderColumnName();
61
        $primaryKeyColumn = $model->getKeyName();
62
63
        foreach ($ids as $id) {
64
            static::where($primaryKeyColumn, $id)->update([$orderColumnName => $startOrder++]);
65
        }
66
    }
67
68
    /**
69
     * Determine the column name of the order column.
70
     *
71
     * @return string
72
     */
73
    protected function determineOrderColumnName()
74
    {
75
        if (
76
            isset($this->sortable['order_column_name']) &&
77
            ! empty($this->sortable['order_column_name'])
78
        ) {
79
            return $this->sortable['order_column_name'];
80
        }
81
82
        return 'order_column';
83
    }
84
85
    /**
86
     * Determine if the order column should be set when saving a new model instance.
87
     *
88
     * @return bool
89
     */
90
    public function shouldSortWhenCreating()
91
    {
92
        if (! isset($this->sortable)) {
93
            return true;
94
        }
95
96
        if (! isset($this->sortable['sort_when_creating'])) {
97
            return true;
98
        }
99
100
        return $this->sortable['sort_when_creating'];
101
    }
102
103
    /**
104
     * Swaps the order of this model with the model 'below' this model.
105
     *
106
     * @return $this
107
     */
108 View Code Duplication
    public function moveOrderDown()
109
    {
110
        $orderColumnName = $this->determineOrderColumnName();
111
112
        $swapWithModel = static::limit(1)
113
            ->ordered()
114
            ->where($orderColumnName, '>', $this->$orderColumnName)
115
            ->first();
116
117
        if (! $swapWithModel) {
118
            return $this;
119
        }
120
121
        return $this->swapOrderWithModel($swapWithModel);
122
    }
123
124
    /**
125
     * Swaps the order of this model with the model 'above' this model.
126
     *
127
     * @return $this
128
     */
129 View Code Duplication
    public function moveOrderUp()
130
    {
131
        $orderColumnName = $this->determineOrderColumnName();
132
133
        $swapWithModel = static::limit(1)
134
            ->ordered('desc')
135
            ->where($orderColumnName, '<', $this->$orderColumnName)
136
            ->first();
137
138
        if (! $swapWithModel) {
139
            return $this;
140
        }
141
142
        return $this->swapOrderWithModel($swapWithModel);
143
    }
144
145
    /**
146
     * Swap the order of this model with the order of another model.
147
     *
148
     * @param \Spatie\EloquentSortable\Sortable $otherModel
149
     *
150
     * @return $this
151
     */
152
    public function swapOrderWithModel(Sortable $otherModel)
153
    {
154
        $orderColumnName = $this->determineOrderColumnName();
155
156
        $oldOrderOfOtherModel = $otherModel->$orderColumnName;
157
158
        $otherModel->$orderColumnName = $this->$orderColumnName;
159
        $otherModel->save();
160
161
        $this->$orderColumnName = $oldOrderOfOtherModel;
162
        $this->save();
163
164
        return $this;
165
    }
166
167
    /**
168
     * Swap the order of two models.
169
     *
170
     * @param \Spatie\EloquentSortable\Sortable $model
171
     * @param \Spatie\EloquentSortable\Sortable $otherModel
172
     */
173
    public static function swapOrder(Sortable $model, Sortable $otherModel)
174
    {
175
        $model->swapOrderWithModel($otherModel);
176
    }
177
178
    /**
179
     * Moves this model to the first position.
180
     *
181
     * @return $this
182
     */
183
    public function moveToStart()
184
    {
185
        $firstModel = static::limit(1)
186
            ->ordered()
187
            ->first();
188
189
        if ($firstModel->id === $this->id) {
190
            return $this;
191
        }
192
193
        $orderColumnName = $this->determineOrderColumnName();
194
195
        $this->$orderColumnName = $firstModel->$orderColumnName;
196
        $this->save();
197
198
        static::where($this->getKeyName(), '!=', $this->id)->increment($orderColumnName);
199
200
        return $this;
201
    }
202
203
    /**
204
     * Moves this model to the last position.
205
     *
206
     * @return $this
207
     */
208
    public function moveToEnd()
209
    {
210
        $maxOrder = $this->getHighestOrderNumber();
211
212
        $orderColumnName = $this->determineOrderColumnName();
213
214
        if ($this->$orderColumnName === $maxOrder) {
215
            return $this;
216
        }
217
218
        $oldOrder = $this->$orderColumnName;
219
220
        $this->$orderColumnName = $maxOrder;
221
        $this->save();
0 ignored issues
show
It seems like save() 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...
222
223
        static::where($this->getKeyName(), '!=', $this->id)
224
            ->where($orderColumnName, '>', $oldOrder)
225
            ->decrement($orderColumnName);
226
227
        return $this;
228
    }
229
}
230