Completed
Pull Request — master (#84)
by
unknown
01:19
created

SortableTrait::getNextInOrder()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Spatie\EloquentSortable;
4
5
use ArrayAccess;
6
use Illuminate\Database\Eloquent\Builder;
7
use Illuminate\Database\Eloquent\SoftDeletingScope;
8
use InvalidArgumentException;
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 getNextInOrder()
22
    {
23
        $orderColumn = $this->determineOrderColumnName();
24
25
        return $this->buildSortQuery()
26
            ->ordered()
27
            ->where($orderColumn, '>', $this->$orderColumn)
28
            ->first();
29
    }
30
31
    public function getPreviousInOrder()
32
    {
33
        $orderColumn = $this->determineOrderColumnName();
34
35
        return $this->buildSortQuery()
36
            ->ordered('desc')
37
            ->where($orderColumn, '<', $this->$orderColumn)
38
            ->first();
39
    }
40
41
    public function setHighestOrderNumber()
42
    {
43
        $orderColumnName = $this->determineOrderColumnName();
44
45
        $this->$orderColumnName = $this->getHighestOrderNumber() + 1;
46
    }
47
48
    public function getHighestOrderNumber(): int
49
    {
50
        return (int) $this->buildSortQuery()->max($this->determineOrderColumnName());
51
    }
52
53
    public function scopeOrdered(Builder $query, string $direction = 'asc')
54
    {
55
        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...
56
    }
57
58
    public static function setNewOrder($ids, int $startOrder = 1, string $primaryKeyColumn = null)
59
    {
60
        if (! is_array($ids) && ! $ids instanceof ArrayAccess) {
61
            throw new InvalidArgumentException('You must pass an array or ArrayAccess object to setNewOrder');
62
        }
63
64
        $model = new static;
65
66
        $orderColumnName = $model->determineOrderColumnName();
67
68
        if (is_null($primaryKeyColumn)) {
69
            $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...
70
        }
71
72
        foreach ($ids as $id) {
73
            static::withoutGlobalScope(SoftDeletingScope::class)
74
                ->where($primaryKeyColumn, $id)
75
                ->update([$orderColumnName => $startOrder++]);
76
        }
77
    }
78
79
    public static function setNewOrderByCustomColumn(string $primaryKeyColumn, $ids, int $startOrder = 1)
80
    {
81
        self::setNewOrder($ids, $startOrder, $primaryKeyColumn);
82
    }
83
84
    protected function determineOrderColumnName(): string
85
    {
86
        return $this->sortable['order_column_name'] ?? 'order_column';
0 ignored issues
show
Bug introduced by
The property sortable 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...
87
    }
88
89
    /**
90
     * Determine if the order column should be set when saving a new model instance.
91
     */
92
    public function shouldSortWhenCreating(): bool
93
    {
94
        return $this->sortable['sort_when_creating'] ?? true;
95
    }
96
97 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...
98
    {
99
        $orderColumnName = $this->determineOrderColumnName();
100
101
        $swapWithModel = $this->buildSortQuery()->limit(1)
102
            ->ordered()
103
            ->where($orderColumnName, '>', $this->$orderColumnName)
104
            ->first();
105
106
        if (! $swapWithModel) {
107
            return $this;
108
        }
109
110
        return $this->swapOrderWithModel($swapWithModel);
111
    }
112
113 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...
114
    {
115
        $orderColumnName = $this->determineOrderColumnName();
116
117
        $swapWithModel = $this->buildSortQuery()->limit(1)
118
            ->ordered('desc')
119
            ->where($orderColumnName, '<', $this->$orderColumnName)
120
            ->first();
121
122
        if (! $swapWithModel) {
123
            return $this;
124
        }
125
126
        return $this->swapOrderWithModel($swapWithModel);
127
    }
128
129
    public function swapOrderWithModel(Sortable $otherModel)
130
    {
131
        $orderColumnName = $this->determineOrderColumnName();
132
133
        $oldOrderOfOtherModel = $otherModel->$orderColumnName;
134
135
        $otherModel->$orderColumnName = $this->$orderColumnName;
136
        $otherModel->save();
137
138
        $this->$orderColumnName = $oldOrderOfOtherModel;
139
        $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...
140
141
        return $this;
142
    }
143
144
    public static function swapOrder(Sortable $model, Sortable $otherModel)
145
    {
146
        $model->swapOrderWithModel($otherModel);
147
    }
148
149
    public function moveToStart()
150
    {
151
        $firstModel = $this->buildSortQuery()->limit(1)
152
            ->ordered()
153
            ->first();
154
155
        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...
156
            return $this;
157
        }
158
159
        $orderColumnName = $this->determineOrderColumnName();
160
161
        $this->$orderColumnName = $firstModel->$orderColumnName;
162
        $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...
163
164
        $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...
165
166
        return $this;
167
    }
168
169
    public function moveToEnd()
170
    {
171
        $maxOrder = $this->getHighestOrderNumber();
172
173
        $orderColumnName = $this->determineOrderColumnName();
174
175
        if ($this->$orderColumnName === $maxOrder) {
176
            return $this;
177
        }
178
179
        $oldOrder = $this->$orderColumnName;
180
181
        $this->$orderColumnName = $maxOrder;
182
        $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...
183
184
        $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...
185
            ->where($orderColumnName, '>', $oldOrder)
186
            ->decrement($orderColumnName);
187
188
        return $this;
189
    }
190
191
    public function buildSortQuery()
192
    {
193
        return static::query();
194
    }
195
}
196