Completed
Pull Request — master (#19)
by
unknown
04:54 queued 02:38
created

SortableTrait::shouldSortWhenCreating()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 12
Ratio 100 %

Importance

Changes 0
Metric Value
dl 12
loc 12
c 0
b 0
f 0
rs 9.4285
cc 3
eloc 6
nc 3
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
        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 View Code Duplication
    public function shouldSortWhenCreating()
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...
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
     * Determine if the table should be reorder when deleting
101
     *
102
     * @return bool
103
     */
104 View Code Duplication
    public function shouldSortWhenDeleting()
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
        if (!isset($this->sortable)) {
107
            return true;
108
        }
109
110
        if (!isset($this->sortable['sort_when_deleting'])) {
111
            return true;
112
        }
113
114
        return $this->sortable['sort_when_deleting'];
115
    }
116
117
    /**
118
     * Swaps the order of this model with the model 'below' this model.
119
     *
120
     * @return $this
121
     */
122 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...
123
    {
124
        $orderColumnName = $this->determineOrderColumnName();
125
126
        $swapWithModel = static::limit(1)
127
            ->ordered()
128
            ->where($orderColumnName, '>', $this->$orderColumnName)
129
            ->first();
130
131
        if (!$swapWithModel) {
132
            return $this;
133
        }
134
135
        return $this->swapOrderWithModel($swapWithModel);
136
    }
137
138
    /**
139
     * Swaps the order of this model with the model 'above' this model.
140
     *
141
     * @return $this
142
     */
143 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...
144
    {
145
        $orderColumnName = $this->determineOrderColumnName();
146
147
        $swapWithModel = static::limit(1)
148
            ->ordered('desc')
149
            ->where($orderColumnName, '<', $this->$orderColumnName)
150
            ->first();
151
152
        if (!$swapWithModel) {
153
            return $this;
154
        }
155
156
        return $this->swapOrderWithModel($swapWithModel);
157
    }
158
159
    /**
160
     * Swap the order of this model with the order of another model.
161
     *
162
     * @param \Spatie\EloquentSortable\Sortable $model
163
     *
164
     * @return $this
165
     */
166
    protected function swapOrderWithModel(self $model)
167
    {
168
        $orderColumnName = $this->determineOrderColumnName();
169
        $oldOrderOfOtherModel = $model->$orderColumnName;
170
171
        $model->$orderColumnName = $this->$orderColumnName;
172
        $model->save();
173
174
        $this->$orderColumnName = $oldOrderOfOtherModel;
175
        $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...
176
177
        return $this;
178
    }
179
180
    /**
181
     * Reorder the records
182
     */
183
    public function reorder()
184
    {
185
        $order = 1;
186
187
        $orderColumnName = $this->determineOrderColumnName();
188
189
        foreach (self::ordered()->select([$this->getKeyName(), $orderColumnName])->get() as $model) {
0 ignored issues
show
Bug introduced by
The method ordered() does not exist on Spatie\EloquentSortable\SortableTrait. Did you maybe mean scopeOrdered()?

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...
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...
190
191
            if ((int) $model->$orderColumnName !== $order) {
192
                $model->$orderColumnName = $order;
193
                $model->save();
194
            }
195
196
            $order++;
197
        }
198
199
    }
200
}
201