Completed
Pull Request — master (#38)
by
unknown
08:54
created

SortableTrait::bootSortableTrait()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 3
eloc 4
nc 1
nop 0
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
    /**
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 Record with the highest order (located at the "End").
33
     *
34
     * @return int
35
     */
36
    public function getHighestOrderNumber(): int
37
    {
38
        if ($this->hasSortScope()) {
39
            return static::where($this->determineSortScope(), $this->{$this->determineSortScope()})
40
                ->max($this->determineOrderColumnName());
41
        }
42
43
        return (int) static::max($this->determineOrderColumnName());
44
    }
45
46
    /**
47
     * Let's be nice and provide an ordered scope.
48
     *
49
     * @param \Illuminate\Database\Eloquent\Builder $query
50
     * @param string $direction
51
     *
52
     * @return \Illuminate\Database\Query\Builder
53
     */
54
    public function scopeOrdered(Builder $query, string $direction = 'asc')
55
    {
56
        return $query->orderBy($this->determineOrderColumnName(), $direction);
0 ignored issues
show
Bug introduced by
The method orderBy() does not exist on Illuminate\Database\Eloquent\Builder. Did you maybe mean enforceOrderBy()?

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...
57
    }
58
59
    /**
60
     * This function reorders the records: the record with the first id in the array
61
     * will get order 1, the record with the second it will get order 2, ...
62
     *
63
     * A starting order number can be optionally supplied (defaults to 1).
64
     *
65
     * @param array|\ArrayAccess $ids
66
     * @param int $startOrder
67
     */
68
    public static function setNewOrder($ids, int $startOrder = 1)
69
    {
70
        if (! is_array($ids) && ! $ids instanceof ArrayAccess) {
71
            throw new InvalidArgumentException('You must pass an array or ArrayAccess object to setNewOrder');
72
        }
73
74
        $model = new static;
75
76
        $orderColumnName = $model->determineOrderColumnName();
77
        $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...
78
79
        foreach ($ids as $id) {
80
            static::withoutGlobalScope(SoftDeletingScope::class)
81
                ->where($primaryKeyColumn, $id)
82
                ->update([$orderColumnName => $startOrder++]);
83
        }
84
    }
85
86
    /*
87
     * Determine the column name of the order column.
88
     */
89
    protected function determineOrderColumnName(): string
90
    {
91
        if (
92
            isset($this->sortable['order_column_name']) &&
93
            ! empty($this->sortable['order_column_name'])
94
        ) {
95
            return $this->sortable['order_column_name'];
96
        }
97
98
        return 'order_column';
99
    }
100
101
    public function determineSortScope() {
102
        if (
103
            isset($this->sortable['sort_scope']) &&
104
            ! empty($this->sortable['sort_scope'])
105
        ) {
106
            return $this->sortable['sort_scope'];
107
        }
108
109
        return '';
110
    }
111
112
    public function hasSortScope() {
113
        return !empty($this->determineSortScope());
114
    }
115
116
    /**
117
     * Determine if the order column should be set when saving a new model instance.
118
     */
119
    public function shouldSortWhenCreating(): bool
120
    {
121
        return $this->sortable['sort_when_creating'] ?? true;
122
    }
123
124
    /**
125
     * Swaps the order of this model with the model 'below' this model.
126
     *
127
     * @return $this
128
     */
129 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...
130
    {
131
        $orderColumnName = $this->determineOrderColumnName();
132
133
        $swapWithModel = static::limit(1)
134
            ->ordered()
135
            ->where($orderColumnName, '>', $this->$orderColumnName);
136
137
138
        if ($this->hasSortScope()) {
139
            $swapWithModel = $swapWithModel->where($this->determineSortScope(), $this->{$this->determineSortScope()});
140
        }
141
142
        $swapWithModel = $swapWithModel->first();
143
144
        if (! $swapWithModel) {
145
            return $this;
146
        }
147
148
        return $this->swapOrderWithModel($swapWithModel);
149
    }
150
        
151
    /**
152
     * Swaps the order of this model with the model 'above' this model.
153
     *
154
     * @return $this
155
     */
156 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...
157
    {
158
        $orderColumnName = $this->determineOrderColumnName();
159
160
        $swapWithModel = static::limit(1)
161
            ->ordered('desc')
162
            ->where($orderColumnName, '<', $this->$orderColumnName);
163
164
        if ($this->hasSortScope()) {
165
            $swapWithModel = $swapWithModel->where($this->determineSortScope(), $this->{$this->determineSortScope()});
166
        }
167
168
        $swapWithModel = $swapWithModel->first();
169
170
        if (! $swapWithModel) {
171
            return $this;
172
        }
173
174
        return $this->swapOrderWithModel($swapWithModel);
175
    }
176
177
    /**
178
     * Swap the order of this model with the order of another model.
179
     *
180
     * @param \Spatie\EloquentSortable\Sortable $otherModel
181
     *
182
     * @return $this
183
     */
184
    public function swapOrderWithModel(Sortable $otherModel)
185
    {
186
        $orderColumnName = $this->determineOrderColumnName();
187
188
        $oldOrderOfOtherModel = $otherModel->$orderColumnName;
189
190
        $otherModel->$orderColumnName = $this->$orderColumnName;
191
        $otherModel->save();
192
193
        $this->$orderColumnName = $oldOrderOfOtherModel;
194
        $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...
195
196
        return $this;
197
    }
198
199
    /**
200
     * Swap the order of two models.
201
     *
202
     * @param \Spatie\EloquentSortable\Sortable $model
203
     * @param \Spatie\EloquentSortable\Sortable $otherModel
204
     */
205
    public static function swapOrder(Sortable $model, Sortable $otherModel)
206
    {
207
        $model->swapOrderWithModel($otherModel);
208
    }
209
210
    /**
211
     * Moves this model to the first position.
212
     *
213
     * @return $this
214
     */
215
    public function moveToStart()
216
    {
217
        $firstModel = static::limit(1)
218
            ->ordered()
219
            ->first();
220
221
        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...
222
            return $this;
223
        }
224
225
        $orderColumnName = $this->determineOrderColumnName();
226
227
        $this->$orderColumnName = $firstModel->$orderColumnName;
228
        $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...
229
230
        $fixOtherRecords = 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...
231
        
232
        if ($this->hasSortScope()) {
233
            $fixOtherRecords = $fixOtherRecords->where($this->determineSortScope(), $this->{$this->determineSortScope()});
234
        }
235
            
236
        $fixOtherRecords->increment($orderColumnName);
237
238
        return $this;
239
    }
240
241
    /**
242
     * Moves this model to the last position.
243
     *
244
     * @return $this
245
     */
246
    public function moveToEnd()
247
    {
248
        $maxOrder = $this->getHighestOrderNumber();
249
250
        $orderColumnName = $this->determineOrderColumnName();
251
252
        if ($this->$orderColumnName === $maxOrder) {
253
            return $this;
254
        }
255
256
        $oldOrder = $this->$orderColumnName;
257
258
        $this->$orderColumnName = $maxOrder;
259
        $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...
260
261
        $fixOtherRecords = 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...
262
            ->where($orderColumnName, '>', $oldOrder);
263
264
        if ($this->hasSortScope()) {
265
            $fixOtherRecords = $fixOtherRecords->where($this->determineSortScope(), $this->{$this->determineSortScope()});
266
        }
267
268
        $fixOtherRecords->decrement($orderColumnName);
269
270
        return $this;
271
    }
272
}
273