Completed
Push — master ( 590ad2...37f4aa )
by Freek
02:11
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
7
trait SortableTrait
8
{
9
    public static function bootSortableTrait()
10
    {
11
        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...
12
            if ($model instanceof Sortable && $model->shouldSortWhenCreating()) {
13
                $model->setHighestOrderNumber();
14
            }
15
        });
16
    }
17
18
    /**
19
     * Modify the order column value.
20
     */
21
    public function setHighestOrderNumber()
22
    {
23
        $orderColumnName = $this->determineOrderColumnName();
24
        $this->$orderColumnName = $this->getHighestOrderNumber() + 1;
25
    }
26
27
    /**
28
     * Determine the order value for the new record.
29
     *
30
     * @return int
31
     */
32
    public function getHighestOrderNumber()
33
    {
34
        return (int)static::max($this->determineOrderColumnName());
35
    }
36
37
    /**
38
     * Let's be nice and provide an ordered scope.
39
     *
40
     * @param \Illuminate\Database\Eloquent\Builder $query
41
     * @param string $direction
42
     *
43
     * @return \Illuminate\Database\Query\Builder
44
     */
45
    public function scopeOrdered(\Illuminate\Database\Eloquent\Builder $query, $direction = 'asc')
46
    {
47
        return $query->orderBy($this->determineOrderColumnName(), $direction);
48
    }
49
50
    /**
51
     * This function reorders the records: the record with the first id in the array
52
     * will get order 1, the record with the second it will get order 2, ...
53
     *
54
     * A starting order number can be optionally supplied (defaults to 1).
55
     *
56
     * @param array $ids
57
     * @param int $startOrder
58
     *
59
     * @throws SortableException
60
     */
61
    public static function setNewOrder($ids, $startOrder = 1)
62
    {
63
        if (!is_array($ids) && !$ids instanceof ArrayAccess) {
64
            throw new SortableException('You must pass an array or ArrayAccess object to setNewOrder');
0 ignored issues
show
Deprecated Code introduced by
The class Spatie\EloquentSortable\SortableException has been deprecated with message: This class will be removed in the next major version.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
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::where($primaryKeyColumn, $id)->update([$orderColumnName => $startOrder++]);
74
        }
75
    }
76
77
    /**
78
     * Determine the column name of the order column.
79
     *
80
     * @return string
81
     */
82
    protected function determineOrderColumnName()
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 if the order column should be set when saving a new model instance.
96
     *
97
     * @return bool
98
     */
99
    public function shouldSortWhenCreating()
100
    {
101
        if (!isset($this->sortable)) {
102
            return true;
103
        }
104
105
        if (!isset($this->sortable['sort_when_creating'])) {
106
            return true;
107
        }
108
109
        return $this->sortable['sort_when_creating'];
110
    }
111
112
    /**
113
     * Swaps the order of this model with the model 'below' this model.
114
     *
115
     * @return $this
116
     */
117 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...
118
    {
119
        $orderColumnName = $this->determineOrderColumnName();
120
121
        $swapWithModel = static::limit(1)
122
            ->ordered()
123
            ->where($orderColumnName, '>', $this->$orderColumnName)
124
            ->first();
125
126
        if (!$swapWithModel) {
127
            return $this;
128
        }
129
130
        return $this->swapOrderWithModel($swapWithModel);
131
    }
132
133
    /**
134
     * Swaps the order of this model with the model 'above' this model.
135
     *
136
     * @return $this
137
     */
138 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...
139
    {
140
        $orderColumnName = $this->determineOrderColumnName();
141
142
        $swapWithModel = static::limit(1)
143
            ->ordered('desc')
144
            ->where($orderColumnName, '<', $this->$orderColumnName)
145
            ->first();
146
147
        if (!$swapWithModel) {
148
            return $this;
149
        }
150
151
        return $this->swapOrderWithModel($swapWithModel);
152
    }
153
154
    /**
155
     * Swap the order of this model with the order of another model.
156
     *
157
     * @param \Spatie\EloquentSortable\Sortable $otherModel
158
     *
159
     * @return $this
160
     */
161
    public function swapOrderWithModel(Sortable $otherModel)
162
    {
163
        $orderColumnName = $this->determineOrderColumnName();
164
165
        $oldOrderOfOtherModel = $otherModel->$orderColumnName;
166
167
        $otherModel->$orderColumnName = $this->$orderColumnName;
168
        $otherModel->save();
169
170
        $this->$orderColumnName = $oldOrderOfOtherModel;
171
        $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...
172
173
        return $this;
174
    }
175
176
    /**
177
     * Swap the order of two models.
178
     *
179
     * @param \Spatie\EloquentSortable\Sortable $model
180
     * @param \Spatie\EloquentSortable\Sortable $otherModel
181
     */
182
    public static function swapOrder(Sortable $model, Sortable $otherModel)
183
    {
184
        $model->swapOrderWithModel($otherModel);
185
    }
186
187
    /**
188
     * Moves this model to the first position.
189
     *
190
     * @return $this
191
     */
192
    public function moveToStart()
193
    {
194
        $firstModel = static::limit(1)
195
            ->ordered()
196
            ->first();
197
198
        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...
199
            return $this;
200
        }
201
202
        $orderColumnName = $this->determineOrderColumnName();
203
204
        $this->$orderColumnName = $firstModel->$orderColumnName;
205
        $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...
206
207
        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...
208
209
        return $this;
210
    }
211
212
    /**
213
     * Moves this model to the last position.
214
     *
215
     * @return $this
216
     */
217
    public function moveToEnd()
218
    {
219
        $maxOrder = $this->getHighestOrderNumber();
220
221
        $orderColumnName = $this->determineOrderColumnName();
222
223
        if ($this->$orderColumnName === $maxOrder) {
224
            return $this;
225
        }
226
227
        $oldOrder = $this->$orderColumnName;
228
229
        $this->$orderColumnName = $maxOrder;
230
        $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...
231
232
        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...
233
            ->where($orderColumnName, '>', $oldOrder)
234
            ->decrement($orderColumnName);
235
236
        return $this;
237
    }
238
}
239