Completed
Pull Request — master (#36)
by
unknown
01:57
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
use ArrayAccess;
6
use InvalidArgumentException;
7
use Illuminate\Database\Eloquent\Builder;
8
use Illuminate\Database\Eloquent\SoftDeletingScope;
9
10
trait SortableTrait
11
{
12
    public static function bootSortableTrait()
13
    {
14
        static::creating(function ($model) {
0 ignored issues
show
Bug introduced by
The method creating() does not exist on Spatie\EloquentSortable\SortableTrait. Did you maybe mean shouldSortWhenCreating()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
15
            if ($model instanceof Sortable && $model->shouldSortWhenCreating()) {
16
                $model->setHighestOrderNumber();
17
            }
18
        });
19
    }
20
21
    abstract public function newQuery();
22
23
    /**
24
     * Modify the order column value.
25
     */
26
    public function setHighestOrderNumber()
27
    {
28
        $orderColumnName = $this->determineOrderColumnName();
29
30
        $this->$orderColumnName = $this->getHighestOrderNumber() + 1;
31
    }
32
33
    /**
34
     * Determine the order value for the new record.
35
     */
36
    public function getHighestOrderNumber(): int
37
    {
38
        return (int) static::applySortableGroup($this->newQuery(), $this)->max($this->determineOrderColumnName());
39
    }
40
41
    /**
42
     * Let's be nice and provide an ordered scope.
43
     *
44
     * @param \Illuminate\Database\Eloquent\Builder $query
45
     * @param string $direction
46
     *
47
     * @return \Illuminate\Database\Query\Builder
48
     */
49
    public function scopeOrdered(Builder $query, string $direction = 'asc')
50
    {
51
        return $query->orderBy($this->determineOrderColumnName(), $direction);
52
    }
53
54
    /**
55
     * This function reorders the records: the record with the first id in the array
56
     * will get order 1, the record with the second it will get order 2, ...
57
     *
58
     * A starting order number can be optionally supplied (defaults to 1).
59
     *
60
     * @param array|\ArrayAccess $ids
61
     * @param int $startOrder
62
     */
63
    public static function setNewOrder($ids, int $startOrder = 1)
64
    {
65
        if (! is_array($ids) && ! $ids instanceof ArrayAccess) {
66
            throw new InvalidArgumentException('You must pass an array or ArrayAccess object to setNewOrder');
67
        }
68
69
        $model = new static;
70
71
        $orderColumnName = $model->determineOrderColumnName();
72
        $primaryKeyColumn = $model->getKeyName();
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...
73
74
        foreach ($ids as $id) {
75
            static::applySortableGroup($this->newQuery(), $this)->withoutGlobalScope(SoftDeletingScope::class)
0 ignored issues
show
Bug introduced by
The variable $this does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
76
                ->where($primaryKeyColumn, $id)
77
                ->update([$orderColumnName => $startOrder++]);
78
        }
79
    }
80
81
    /*
82
     * Determine the column name of the order column.
83
     */
84
    protected function determineOrderColumnName(): string
85
    {
86
        if (
87
            isset($this->sortable['order_column_name']) &&
88
            ! empty($this->sortable['order_column_name'])
89
        ) {
90
            return $this->sortable['order_column_name'];
91
        }
92
93
        return 'order_column';
94
    }
95
96
    /**
97
     * Determine if the order column should be set when saving a new model instance.
98
     */
99
    public function shouldSortWhenCreating(): bool
100
    {
101
        return $this->sortable['sort_when_creating'] ?? true;
102
    }
103
104
    /**
105
     * Swaps the order of this model with the model 'below' this model.
106
     *
107
     * @return $this
108
     */
109 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...
110
    {
111
        $orderColumnName = $this->determineOrderColumnName();
112
113
        $swapWithModel = static::applySortableGroup($this->newQuery(), $this)->limit(1)
114
            ->ordered()
115
            ->where($orderColumnName, '>', $this->$orderColumnName)
116
            ->first();
117
118
        if (! $swapWithModel) {
119
            return $this;
120
        }
121
122
        return $this->swapOrderWithModel($swapWithModel);
123
    }
124
125
    /**
126
     * Swaps the order of this model with the model 'above' this model.
127
     *
128
     * @return $this
129
     */
130 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...
131
    {
132
        $orderColumnName = $this->determineOrderColumnName();
133
134
        $swapWithModel = static::applySortableGroup($this->newQuery(), $this)->limit(1)
135
            ->ordered('desc')
136
            ->where($orderColumnName, '<', $this->$orderColumnName)
137
            ->first();
138
139
        if (! $swapWithModel) {
140
            return $this;
141
        }
142
143
        return $this->swapOrderWithModel($swapWithModel);
144
    }
145
146
    /**
147
     * Swap the order of this model with the order of another model.
148
     *
149
     * @param \Spatie\EloquentSortable\Sortable $otherModel
150
     *
151
     * @return $this
152
     */
153
    public function swapOrderWithModel(Sortable $otherModel)
154
    {
155
        $orderColumnName = $this->determineOrderColumnName();
156
157
        $oldOrderOfOtherModel = $otherModel->$orderColumnName;
158
159
        $otherModel->$orderColumnName = $this->$orderColumnName;
160
        $otherModel->save();
161
162
        $this->$orderColumnName = $oldOrderOfOtherModel;
163
        $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...
164
165
        return $this;
166
    }
167
168
    /**
169
     * Swap the order of two models.
170
     *
171
     * @param \Spatie\EloquentSortable\Sortable $model
172
     * @param \Spatie\EloquentSortable\Sortable $otherModel
173
     */
174
    public static function swapOrder(Sortable $model, Sortable $otherModel)
175
    {
176
        $model->swapOrderWithModel($otherModel);
177
    }
178
179
    /**
180
     * Moves this model to the first position.
181
     *
182
     * @return $this
183
     */
184
    public function moveToStart()
185
    {
186
        $firstModel = static::limit(1)
187
            ->ordered()
188
            ->first();
189
190
        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...
191
            return $this;
192
        }
193
194
        $orderColumnName = $this->determineOrderColumnName();
195
196
        $this->$orderColumnName = $firstModel->$orderColumnName;
197
        $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...
198
199
        static::applySortableGroup($this->newQuery(), $this)->where($this->getKeyName(), '!=', $this->id)->increment($orderColumnName);
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...
200
201
        return $this;
202
    }
203
204
    /**
205
     * Moves this model to the last position.
206
     *
207
     * @return $this
208
     */
209
    public function moveToEnd()
210
    {
211
        $maxOrder = $this->getHighestOrderNumber();
212
213
        $orderColumnName = $this->determineOrderColumnName();
214
215
        if ($this->$orderColumnName === $maxOrder) {
216
            return $this;
217
        }
218
219
        $oldOrder = $this->$orderColumnName;
220
221
        $this->$orderColumnName = $maxOrder;
222
        $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...
223
224
        static::applySortableGroup($this->newQuery(), $this)->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...
225
            ->where($orderColumnName, '>', $oldOrder)
226
            ->decrement($orderColumnName);
227
228
        return $this;
229
    }
230
231
    /**
232
     * @param QueryBuilder        $query
233
     * @param Model|SortableTrait $model
234
     *
235
     * @return QueryBuilder
236
     */
237
    protected static function applySortableGroup($query, $model) {
238
239
        $sortableGroupField = static::getSortableGroupField();
240
241
        if (is_array($sortableGroupField)) {
242
            foreach ($sortableGroupField as $field) {
243
                $query = $query->where($field, $model->$field);
244
            }
245
        } elseif ($sortableGroupField !== null) {
246
            $query = $query->where($sortableGroupField, $model->$sortableGroupField);
247
        }
248
249
        return $query;
250
    }
251
252
    /**
253
     * @return string|null
254
     */
255
    public static function getSortableGroupField() {
256
        $sortableGroupField = isset($this->sortable['sort_by_group_column']) ? $this->sortable['sort_by_group_column'] : null;
0 ignored issues
show
Bug introduced by
The variable $this does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
257
        return $sortableGroupField;
258
    }
259
260
}
261