Completed
Pull Request — master (#24)
by
unknown
07:29 queued 05:05
created

SortableTrait::determineOrderColumnName()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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