Completed
Pull Request — master (#56)
by
unknown
01:55 queued 11s
created

SortableTrait::getGroupColumnValue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
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 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
     */
61
    public static function setNewOrder($ids, int $startOrder = 1)
62
    {
63
        if (! is_array($ids) && ! $ids instanceof ArrayAccess) {
64
            throw new InvalidArgumentException('You must pass an array or ArrayAccess object to setNewOrder');
65
        }
66
67
        $model = new static;
68
69
        $orderColumnName = $model->determineOrderColumnName();
70
        $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...
71
72
        foreach ($ids as $id) {
73
            static::withoutGlobalScope(SoftDeletingScope::class)
74
                ->where($primaryKeyColumn, $id)
75
                ->update([$orderColumnName => $startOrder++]);
76
        }
77
    }
78
79
    /*
80
     * Determine the column name of the order column.
81
     */
82
    protected function determineOrderColumnName(): string
83
    {
84
        if (
85
            isset($this->sortable['order_column_name']) &&
86
            ! empty($this->sortable['order_column_name'])
87
        ) {
88
            return $this->sortable['order_column_name'];
89
        }
90
91
        return 'order_column';
92
    }
93
94
    /*
95
     * Determine the column name of the group column.
96
     */
97
    protected function determineGroupColumnName(): string
98
    {
99
        if (
100
            isset($this->sortable['group_column_name']) &&
101
            ! empty($this->sortable['group_column_name'])
102
        ) {
103
            return $this->sortable['group_column_name'];
104
        }
105
106
        return 'group_column';
107
    }
108
109
    /**
110
     * Determine the order value for the new record.
111
     */
112
    public function getGroupColumnValue()
113
    {
114
        $groupColumnName = $this->determineGroupColumnName();
115
116
        return $this->$groupColumnName;
117
    }
118
119
    /**
120
     * Determine if it should be sorted by group column.
121
     */
122
    public function shouldSortByGroup(): bool
123
    {
124
        return $this->sortable['sort_by_group'] ?? false;
125
    }
126
127
    /**
128
     * Determine if the order column should be set when saving a new model instance.
129
     */
130
    public function shouldSortWhenCreating(): bool
131
    {
132
        return $this->sortable['sort_when_creating'] ?? true;
133
    }
134
135
    /**
136
     * Swaps the order of this model with the model 'below' this model.
137
     *
138
     * @return $this
139
     */
140 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...
141
    {
142
        $orderColumnName = $this->determineOrderColumnName();
143
144
        $swapWithModel = $this->buildSortQuery()->limit(1)
145
            ->ordered()
146
            ->where($orderColumnName, '>', $this->$orderColumnName)
147
            ->first();
148
149
        if (! $swapWithModel) {
150
            return $this;
151
        }
152
153
        return $this->swapOrderWithModel($swapWithModel);
154
    }
155
156
    /**
157
     * Swaps the order of this model with the model 'above' this model.
158
     *
159
     * @return $this
160
     */
161 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...
162
    {
163
        $orderColumnName = $this->determineOrderColumnName();
164
165
        $swapWithModel = $this->buildSortQuery()->limit(1)
166
            ->ordered('desc')
167
            ->where($orderColumnName, '<', $this->$orderColumnName)
168
            ->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 = $this->buildSortQuery()->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
        $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...
231
232
        return $this;
233
    }
234
235
    /**
236
     * Moves this model to the last position.
237
     *
238
     * @return $this
239
     */
240
    public function moveToEnd()
241
    {
242
        $maxOrder = $this->getHighestOrderNumber();
243
244
        $orderColumnName = $this->determineOrderColumnName();
245
246
        if ($this->$orderColumnName === $maxOrder) {
247
            return $this;
248
        }
249
250
        $oldOrder = $this->$orderColumnName;
251
252
        $this->$orderColumnName = $maxOrder;
253
        $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...
254
255
        $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...
256
            ->where($orderColumnName, '>', $oldOrder)
257
            ->decrement($orderColumnName);
258
259
        return $this;
260
    }
261
262
    /**
263
     * Build eloquent builder of sortable.
264
     *
265
     * @return \Illuminate\Database\Eloquent\Builder
266
     */
267
    public function buildSortQuery()
268
    {
269
        if ($this->shouldSortByGroup() && $groupColumnName = $this->determineGroupColumnName()) {
270
            return static::query()->where($groupColumnName, $this->getGroupColumnValue());
271
        } else {
272
            return static::query();
273
        }
274
    }
275
}
276