Completed
Pull Request — master (#22)
by
unknown
02:25
created

SortableTrait   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 210
Duplicated Lines 14.29 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
dl 30
loc 210
c 0
b 0
f 0
wmc 21
lcom 1
cbo 1
rs 10

11 Methods

Rating   Name   Duplication   Size   Complexity  
A setHighestOrderNumber() 0 5 1
A getHighestOrderNumber() 0 4 1
A scopeOrdered() 0 4 1
A setNewOrder() 0 13 3
A determineOrderColumnName() 0 11 3
A shouldSortWhenCreating() 0 12 3
A moveOrderDown() 15 15 2
A moveOrderUp() 15 15 2
A swapOrderWithModel() 0 13 1
A moveToStart() 0 20 2
A moveToEnd() 0 21 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
        foreach ($ids as $id) {
57
            $model = static::find($id);
58
            $orderColumnName = $model->determineOrderColumnName();
59
            $model->$orderColumnName = $startOrder++;
60
            $model->save();
61
        }
62
    }
63
64
    /**
65
     * Determine the column name of the order column.
66
     *
67
     * @return string
68
     */
69
    protected function determineOrderColumnName()
70
    {
71
        if (
72
            isset($this->sortable['order_column_name']) &&
73
            !empty($this->sortable['order_column_name'])
74
        ) {
75
            return $this->sortable['order_column_name'];
76
        }
77
78
        return 'order_column';
79
    }
80
81
    /**
82
     * Determine if the order column should be set when saving a new model instance.
83
     *
84
     * @return bool
85
     */
86
    public function shouldSortWhenCreating()
87
    {
88
        if (!isset($this->sortable)) {
89
            return true;
90
        }
91
92
        if (!isset($this->sortable['sort_when_creating'])) {
93
            return true;
94
        }
95
96
        return $this->sortable['sort_when_creating'];
97
    }
98
99
    /**
100
     * Swaps the order of this model with the model 'below' this model.
101
     *
102
     * @return $this
103
     */
104 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...
105
    {
106
        $orderColumnName = $this->determineOrderColumnName();
107
108
        $swapWithModel = static::limit(1)
109
            ->ordered()
110
            ->where($orderColumnName, '>', $this->$orderColumnName)
111
            ->first();
112
113
        if (!$swapWithModel) {
114
            return $this;
115
        }
116
117
        return $this->swapOrderWithModel($swapWithModel);
118
    }
119
120
    /**
121
     * Swaps the order of this model with the model 'above' this model.
122
     *
123
     * @return $this
124
     */
125 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...
126
    {
127
        $orderColumnName = $this->determineOrderColumnName();
128
129
        $swapWithModel = static::limit(1)
130
            ->ordered('desc')
131
            ->where($orderColumnName, '<', $this->$orderColumnName)
132
            ->first();
133
134
        if (!$swapWithModel) {
135
            return $this;
136
        }
137
138
        return $this->swapOrderWithModel($swapWithModel);
139
    }
140
141
    /**
142
     * Swap the order of this model with the order of another model.
143
     *
144
     * @param \Spatie\EloquentSortable\Sortable $model
145
     *
146
     * @return $this
147
     */
148
    protected function swapOrderWithModel(self $model)
149
    {
150
        $orderColumnName = $this->determineOrderColumnName();
151
        $oldOrderOfOtherModel = $model->$orderColumnName;
152
153
        $model->$orderColumnName = $this->$orderColumnName;
154
        $model->save();
155
156
        $this->$orderColumnName = $oldOrderOfOtherModel;
157
        $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...
158
159
        return $this;
160
    }
161
162
    /**
163
     * Moves this model to the first position
164
     *
165
     * @return $this
166
     */
167
    public function moveToStart()
168
    {
169
        $firstModel = static::limit(1)
170
            ->ordered()
171
            ->first();
172
173
        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...
174
            return $this;
175
        }
176
177
        $orderColumnName = $this->determineOrderColumnName();
178
179
        $this->$orderColumnName = $firstModel->$orderColumnName;
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
        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...
183
            ->increment($orderColumnName);
184
185
        return $this;
186
    }
187
188
    /**
189
     * Moves this model to the last position
190
     *
191
     * @return $this
192
     */
193
    public function moveToEnd()
194
    {
195
        $maxOrder = $this->getHighestOrderNumber();
196
197
        $orderColumnName = $this->determineOrderColumnName();
198
199
        if ($this->$orderColumnName == $maxOrder) {
200
            return $this;
201
        }
202
203
        $oldOrder = $this->$orderColumnName;
204
205
        $this->$orderColumnName = $maxOrder;
206
        $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...
207
208
        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...
209
            ->where($orderColumnName, '>', $oldOrder)
210
            ->decrement($orderColumnName);
211
212
        return $this;
213
    }
214
}
215