Passed
Pull Request — 2.x (#597)
by Antonio Carlos
05:31
created

HasPosition   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 12
c 0
b 0
f 0
dl 0
loc 35
ccs 0
cts 26
cp 0
rs 10
wmc 7

5 Methods

Rating   Name   Duplication   Size   Complexity  
A setToLastPosition() 0 3 1
A getCurrentLastPosition() 0 3 1
A setNewOrder() 0 10 3
A scopeOrdered() 0 3 1
A bootHasPosition() 0 4 1
1
<?php
2
3
namespace A17\Twill\Models\Behaviors;
4
5
trait HasPosition
6
{
7
8
    protected static function bootHasPosition()
9
    {
10
        static::creating(function ($model) {
11
            $model->setToLastPosition();
12
        });
13
    }
14
15
    protected function setToLastPosition()
16
    {
17
        $this->position = $this->getCurrentLastPosition() + 1;
0 ignored issues
show
Bug Best Practice introduced by
The property position does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
18
    }
19
20
    protected function getCurrentLastPosition()
21
    {
22
        return ((int) static::max('position'));
23
    }
24
25
    public function scopeOrdered($query)
26
    {
27
        return $query->orderBy('position');
28
    }
29
30
    public static function setNewOrder($ids, $startOrder = 1)
31
    {
32
        if (!is_array($ids)) {
33
            throw new \Exception('You must pass an array to setNewOrder');
34
        }
35
36
        foreach ($ids as $id) {
37
            $model = static::find($id);
38
            $model->position = $startOrder++;
39
            $model->save();
40
        }
41
    }
42
}
43