Completed
Push — master ( f2378d...f54db0 )
by Freek
02:28
created

SortableTrait::swapOrder()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 2
1
<?php
2
3
namespace Spatie\EloquentSortable;
4
5
trait SortableTrait
6
{
7
    /**
8
     * Modify the order column value.
9
     */
10
    public function setHighestOrderNumber()
11
    {
12
        $orderColumnName = $this->determineOrderColumnName();
13
        $this->$orderColumnName = $this->getHighestOrderNumber() + 1;
14
    }
15
16
    /**
17
     * Determine the order value for the new record.
18
     *
19
     * @return int
20
     */
21
    public function getHighestOrderNumber()
22
    {
23
        return (int) static::max($this->determineOrderColumnName());
24
    }
25
26
    /**
27
     * Let's be nice and provide an ordered scope.
28
     *
29
     * @param \Illuminate\Database\Eloquent\Builder $query
30
     * @param string                                $direction
31
     *
32
     * @return \Illuminate\Database\Query\Builder
33
     */
34
    public function scopeOrdered(\Illuminate\Database\Eloquent\Builder $query, $direction = 'asc')
35
    {
36
        return $query->orderBy($this->determineOrderColumnName(), $direction);
37
    }
38
39
    /**
40
     * This function reorders the records: the record with the first id in the array
41
     * will get order 1, the record with the second it will get order 2, ...
42
     *
43
     * A starting order number can be optionally supplied (defaults to 1).
44
     *
45
     * @param array $ids
46
     * @param int   $startOrder
47
     *
48
     * @throws SortableException
49
     */
50
    public static function setNewOrder($ids, $startOrder = 1)
51
    {
52
        if (! is_array($ids)) {
53
            throw new SortableException('You must pass an array 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...
54
        }
55
56
        foreach ($ids as $id) {
57
            $model = static::find($id);
58
            $orderColumnName = $model->determineOrderColumnName();
59
            $model->$orderColumnName = $startOrder++;
60
            $model->save();
61
        }
62
    }
63
64
    /**
65
     * Determine the column name of the order column.
66
     *
67
     * @return string
68
     */
69
    protected function determineOrderColumnName()
70
    {
71
        if (
72
            isset($this->sortable['order_column_name']) &&
73
            ! empty($this->sortable['order_column_name'])
74
        ) {
75
            return $this->sortable['order_column_name'];
76
        }
77
78
        return 'order_column';
79
    }
80
81
    /**
82
     * Determine if the order column should be set when saving a new model instance.
83
     *
84
     * @return bool
85
     */
86
    public function shouldSortWhenCreating()
87
    {
88
        if (! isset($this->sortable)) {
89
            return true;
90
        }
91
92
        if (! isset($this->sortable['sort_when_creating'])) {
93
            return true;
94
        }
95
96
        return $this->sortable['sort_when_creating'];
97
    }
98
99
    /**
100
     * Swaps the order of this model with the model 'below' this model.
101
     *
102
     * @return $this
103
     */
104 View Code Duplication
    public function moveOrderDown()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
105
    {
106
        $orderColumnName = $this->determineOrderColumnName();
107
108
        $swapWithModel = static::limit(1)
109
            ->ordered()
110
            ->where($orderColumnName, '>', $this->$orderColumnName)
111
            ->first();
112
113
        if (! $swapWithModel) {
114
            return $this;
115
        }
116
117
        return $this->swapOrderWithModel($swapWithModel);
118
    }
119
120
    /**
121
     * Swaps the order of this model with the model 'above' this model.
122
     *
123
     * @return $this
124
     */
125 View Code Duplication
    public function moveOrderUp()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
126
    {
127
        $orderColumnName = $this->determineOrderColumnName();
128
129
        $swapWithModel = static::limit(1)
130
            ->ordered('desc')
131
            ->where($orderColumnName, '<', $this->$orderColumnName)
132
            ->first();
133
134
        if (! $swapWithModel) {
135
            return $this;
136
        }
137
138
        return $this->swapOrderWithModel($swapWithModel);
139
    }
140
141
    /**
142
     * Swap the order of this model with the order of another model.
143
     *
144
     * @param \Spatie\EloquentSortable\Sortable $otherModel
145
     *
146
     * @return $this
147
     */
148
    protected function swapOrderWithModel($otherModel)
149
    {
150
        $orderColumnName = $this->determineOrderColumnName();
151
152
        $oldOrderOfOtherModel = $otherModel->$orderColumnName;
153
154
        $otherModel->$orderColumnName = $this->$orderColumnName;
155
        $otherModel->save();
156
157
        $this->$orderColumnName = $oldOrderOfOtherModel;
158
        $this->save();
0 ignored issues
show
Bug introduced by
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...
159
160
        return $this;
161
    }
162
163
    /**
164
     * Swap the order of two models.
165
     *
166
     * @param \Spatie\EloquentSortable\Sortable $model
167
     * @param \Spatie\EloquentSortable\Sortable $model
168
     */
169
    public static function swapOrder(self $model, self $model2)
170
    {
171
        $model->swapOrderWithModel($model2);
172
    }
173
174
    /**
175
     * Moves this model to the first position.
176
     *
177
     * @return $this
178
     */
179
    public function moveToStart()
180
    {
181
        $firstModel = static::limit(1)
182
            ->ordered()
183
            ->first();
184
185
        if ($firstModel->id === $this->id) {
0 ignored issues
show
Bug introduced by
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...
186
            return $this;
187
        }
188
189
        $orderColumnName = $this->determineOrderColumnName();
190
191
        $this->$orderColumnName = $firstModel->$orderColumnName;
192
        $this->save();
0 ignored issues
show
Bug introduced by
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...
193
194
        static::where($this->getKeyName(), '!=', $this->id)
0 ignored issues
show
Bug introduced by
It seems like getKeyName() 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...
195
            ->increment($orderColumnName);
196
197
        return $this;
198
    }
199
200
    /**
201
     * Moves this model to the last position.
202
     *
203
     * @return $this
204
     */
205
    public function moveToEnd()
206
    {
207
        $maxOrder = $this->getHighestOrderNumber();
208
209
        $orderColumnName = $this->determineOrderColumnName();
210
211
        if ($this->$orderColumnName === $maxOrder) {
212
            return $this;
213
        }
214
215
        $oldOrder = $this->$orderColumnName;
216
217
        $this->$orderColumnName = $maxOrder;
218
        $this->save();
0 ignored issues
show
Bug introduced by
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...
219
220
        static::where($this->getKeyName(), '!=', $this->id)
0 ignored issues
show
Bug introduced by
It seems like getKeyName() 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...
221
            ->where($orderColumnName, '>', $oldOrder)
222
            ->decrement($orderColumnName);
223
224
        return $this;
225
    }
226
}
227