Passed
Pull Request — 2.x (#586)
by Bekzat
05:24 queued 25s
created

HasPosition   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Test Coverage

Coverage 16.66%

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 35
ccs 3
cts 18
cp 0.1666
rs 10
c 0
b 0
f 0
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 1
    protected static function bootHasPosition()
9
    {
10
        static::creating(function ($model) {
11
            $model->setToLastPosition();
12 1
        });
13 1
    }
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