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

HasPosition::bootHasPosition()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1.125

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
ccs 1
cts 2
cp 0.5
crap 1.125
rs 10
c 0
b 0
f 0
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