Completed
Pull Request — master (#76)
by
unknown
01:34
created

SortableTrait   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 210
Duplicated Lines 14.29 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

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

16 Methods

Rating   Name   Duplication   Size   Complexity  
A bootSortableTrait() 0 8 3
A determineOrderColumnName() 0 11 3
A shouldSortWhenCreating() 0 4 1
A setHighestOrderNumber() 0 6 1
A getHighestOrderNumber() 0 4 1
A scopeOrdered() 0 4 1
A setOrderAfter() 0 36 5
A setNewOrder() 0 20 5
A setNewOrderByCustomColumn() 0 4 1
A moveOrderDown() 15 15 2
A moveOrderUp() 15 15 2
A swapOrderWithModel() 0 14 1
A swapOrder() 0 4 1
A moveToStart() 0 19 2
A moveToEnd() 0 21 2
A buildSortQuery() 0 4 1

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
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
    public function setHighestOrderNumber()
22
    {
23
        $orderColumnName = $this->determineOrderColumnName();
24
25
        $this->$orderColumnName = $this->getHighestOrderNumber() + 1;
26
    }
27
28
    public function getHighestOrderNumber(): int
29
    {
30
        return (int) $this->buildSortQuery()->max($this->determineOrderColumnName());
31
    }
32
33
    public function scopeOrdered(Builder $query, string $direction = 'asc')
34
    {
35
        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...
36
    }
37
38
    public function setOrderAfter($id)
39
    {
40
        if (! $afterModel = $this->buildSortQuery()->find($id)) {
41
            throw new InvalidArgumentException('You must pass an existing model id');
42
        }
43
44
        if ($afterModel->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...
45
            return $this;
46
        }
47
48
        $orderColumnName = $this->determineOrderColumnName();
49
50
        if ($afterModel->$orderColumnName === $this->$orderColumnName) {
51
            return $this;
52
        }
53
54
        if ($this->$orderColumnName < $afterModel->$orderColumnName) {
55
            $this->buildSortQuery()
56
                ->where($orderColumnName, '>', $this->$orderColumnName)
57
                ->where($orderColumnName, '<=', $afterModel->$orderColumnName)
58
                ->decrement($orderColumnName);
59
60
            return tap($this)->update([
61
                $orderColumnName => $afterModel->$orderColumnName
62
            ]);
63
        }
64
65
        $this->buildSortQuery()
66
            ->where($orderColumnName, '>', $afterModel->$orderColumnName)
67
            ->where($orderColumnName, '<', $this->$orderColumnName)
68
            ->increment($orderColumnName);
69
70
        return tap($this)->update([
71
            $orderColumnName => $afterModel->$orderColumnName + 1
72
        ]);
73
    }
74
75
    public static function setNewOrder($ids, int $startOrder = 1, string $primaryKeyColumn = null)
76
    {
77
        if (! is_array($ids) && ! $ids instanceof ArrayAccess) {
78
            throw new InvalidArgumentException('You must pass an array or ArrayAccess object to setNewOrder');
79
        }
80
81
        $model = new static;
82
83
        $orderColumnName = $model->determineOrderColumnName();
84
85
        if (is_null($primaryKeyColumn)) {
86
            $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...
87
        }
88
89
        foreach ($ids as $id) {
90
            static::withoutGlobalScope(SoftDeletingScope::class)
91
                ->where($primaryKeyColumn, $id)
92
                ->update([$orderColumnName => $startOrder++]);
93
        }
94
    }
95
96
    public static function setNewOrderByCustomColumn(string $primaryKeyColumn, $ids, int $startOrder = 1)
97
    {
98
        self::setNewOrder($ids, $startOrder, $primaryKeyColumn);
99
    }
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 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...
122
    {
123
        $orderColumnName = $this->determineOrderColumnName();
124
125
        $swapWithModel = $this->buildSortQuery()->limit(1)
126
            ->ordered()
127
            ->where($orderColumnName, '>', $this->$orderColumnName)
128
            ->first();
129
130
        if (! $swapWithModel) {
131
            return $this;
132
        }
133
134
        return $this->swapOrderWithModel($swapWithModel);
135
    }
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 = $this->buildSortQuery()->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
    public function swapOrderWithModel(Sortable $otherModel)
154
    {
155
        $orderColumnName = $this->determineOrderColumnName();
156
157
        $oldOrderOfOtherModel = $otherModel->$orderColumnName;
158
159
        $otherModel->$orderColumnName = $this->$orderColumnName;
160
        $otherModel->save();
161
162
        $this->$orderColumnName = $oldOrderOfOtherModel;
163
        $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...
164
165
        return $this;
166
    }
167
168
    public static function swapOrder(Sortable $model, Sortable $otherModel)
169
    {
170
        $model->swapOrderWithModel($otherModel);
171
    }
172
173
    public function moveToStart()
174
    {
175
        $firstModel = $this->buildSortQuery()->limit(1)
176
            ->ordered()
177
            ->first();
178
179
        if ($firstModel->id === $this->id) {
180
            return $this;
181
        }
182
183
        $orderColumnName = $this->determineOrderColumnName();
184
185
        $this->$orderColumnName = $firstModel->$orderColumnName;
186
        $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...
187
188
        $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...
189
190
        return $this;
191
    }
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
        $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...
209
            ->where($orderColumnName, '>', $oldOrder)
210
            ->decrement($orderColumnName);
211
212
        return $this;
213
    }
214
215
    public function buildSortQuery()
216
    {
217
        return static::query();
218
    }
219
}
220