Completed
Pull Request — master (#72)
by Joel
01:27
created

SortableTrait::setNewOrderByCustomColumn()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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