Completed
Pull Request — master (#32)
by Sébastien
06:18
created

SortableTrait::setHighestOrderNumber()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
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) {
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
    /**
22
     * Modify the order column value.
23
     */
24
    public function setHighestOrderNumber()
25
    {
26
        $orderColumnName = $this->determineOrderColumnName();
27
28
        $this->$orderColumnName = $this->getHighestOrderNumber() + 1;
29
    }
30
31
    /**
32
     * Determine the order value for the new record.
33
     */
34
    public function getHighestOrderNumber(): int
35
    {
36
        return (int) static::max($this->determineOrderColumnName());
37
    }
38
39
    /**
40
     * Let's be nice and provide an ordered scope.
41
     *
42
     * @param \Illuminate\Database\Eloquent\Builder $query
43
     * @param string $direction
44
     *
45
     * @return \Illuminate\Database\Query\Builder
46
     */
47
    public function scopeOrdered(Builder $query, string $direction = 'asc')
48
    {
49
        return $query->orderBy($this->determineOrderColumnName(), $direction);
50
    }
51
52
    /**
53
     * Query records which are ordered above the given position.
54
     *
55
     * @param \Illuminate\Database\Eloquent\Builder $query
56
     * @param int $position
57
     *
58
     * @return \Illuminate\Database\Query\Builder
59
     */
60
    public function scopeAbove(Builder $query, int $position)
61
    {
62
        return $query->where($this->determineOrderColumnName(), '<', $position);
63
    }
64
65
    /**
66
     * Query records which are ordered below the given position.
67
     *
68
     * @param \Illuminate\Database\Eloquent\Builder $query
69
     * @param int $position
70
     *
71
     * @return \Illuminate\Database\Query\Builder
72
     */
73
    public function scopeBelow(Builder $query, int $position)
74
    {
75
        return $query->where($this->determineOrderColumnName(), '>', $position);
76
    }
77
78
    /**
79
     * This function reorders the records: the record with the first id in the array
80
     * will get order 1, the record with the second it will get order 2, ...
81
     *
82
     * A starting order number can be optionally supplied (defaults to 1).
83
     *
84
     * @param array|\ArrayAccess $ids
85
     * @param int $startOrder
86
     */
87
    public static function setNewOrder($ids, int $startOrder = 1)
88
    {
89
        if (! is_array($ids) && ! $ids instanceof ArrayAccess) {
90
            throw new InvalidArgumentException('You must pass an array or ArrayAccess object to setNewOrder');
91
        }
92
93
        $model = new static;
94
95
        $orderColumnName = $model->determineOrderColumnName();
96
        $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...
97
98
        foreach ($ids as $id) {
99
            static::withoutGlobalScope(SoftDeletingScope::class)
100
                ->where($primaryKeyColumn, $id)
101
                ->update([$orderColumnName => $startOrder++]);
102
        }
103
    }
104
105
    /*
106
     * Determine the column name of the order column.
107
     */
108
    protected function determineOrderColumnName(): string
109
    {
110
        if (
111
            isset($this->sortable['order_column_name']) &&
112
            ! empty($this->sortable['order_column_name'])
113
        ) {
114
            return $this->sortable['order_column_name'];
115
        }
116
117
        return 'order_column';
118
    }
119
120
    /**
121
     * Determine if the order column should be set when saving a new model instance.
122
     */
123
    public function shouldSortWhenCreating(): bool
124
    {
125
        return $this->sortable['sort_when_creating'] ?? true;
126
    }
127
128
    /**
129
     * Swaps the order of this model with the model 'below' this model.
130
     *
131
     * @return $this
132
     */
133 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...
134
    {
135
        $orderColumnName = $this->determineOrderColumnName();
136
137
        $swapWithModel = static::limit(1)
138
            ->ordered()
139
            ->below($this->$orderColumnName)
140
            ->first();
141
142
        if (! $swapWithModel) {
143
            return $this;
144
        }
145
146
        return $this->swapOrderWithModel($swapWithModel);
147
    }
148
149
    /**
150
     * Swaps the order of this model with the model 'above' this model.
151
     *
152
     * @return $this
153
     */
154 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...
155
    {
156
        $orderColumnName = $this->determineOrderColumnName();
157
158
        $swapWithModel = static::limit(1)
159
            ->ordered('desc')
160
            ->above($this->$orderColumnName)
161
            ->first();
162
163
        if (! $swapWithModel) {
164
            return $this;
165
        }
166
167
        return $this->swapOrderWithModel($swapWithModel);
168
    }
169
170
    /**
171
     * Swap the order of this model with the order of another model.
172
     *
173
     * @param \Spatie\EloquentSortable\Sortable $otherModel
174
     *
175
     * @return $this
176
     */
177
    public function swapOrderWithModel(Sortable $otherModel)
178
    {
179
        $orderColumnName = $this->determineOrderColumnName();
180
181
        $oldOrderOfOtherModel = $otherModel->$orderColumnName;
182
183
        $otherModel->$orderColumnName = $this->$orderColumnName;
184
        $otherModel->save();
185
186
        $this->$orderColumnName = $oldOrderOfOtherModel;
187
        $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...
188
189
        return $this;
190
    }
191
192
    /**
193
     * Swap the order of two models.
194
     *
195
     * @param \Spatie\EloquentSortable\Sortable $model
196
     * @param \Spatie\EloquentSortable\Sortable $otherModel
197
     */
198
    public static function swapOrder(Sortable $model, Sortable $otherModel)
199
    {
200
        $model->swapOrderWithModel($otherModel);
201
    }
202
203
    /**
204
     * Moves this model to the first position.
205
     *
206
     * @return $this
207
     */
208
    public function moveToStart()
209
    {
210
        $firstModel = static::limit(1)
211
            ->ordered()
212
            ->first();
213
214
        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...
215
            return $this;
216
        }
217
218
        $orderColumnName = $this->determineOrderColumnName();
219
220
        $this->$orderColumnName = $firstModel->$orderColumnName;
221
        $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...
222
223
        static::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...
224
225
        return $this;
226
    }
227
228
    /**
229
     * Moves this model to the last position.
230
     *
231
     * @return $this
232
     */
233
    public function moveToEnd()
234
    {
235
        $maxOrder = $this->getHighestOrderNumber();
236
237
        $orderColumnName = $this->determineOrderColumnName();
238
239
        if ($this->$orderColumnName === $maxOrder) {
240
            return $this;
241
        }
242
243
        $oldOrder = $this->$orderColumnName;
244
245
        $this->$orderColumnName = $maxOrder;
246
        $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...
247
248
        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...
249
            ->below($oldOrder)
250
            ->decrement($orderColumnName);
251
252
        return $this;
253
    }
254
}
255