Completed
Pull Request — master (#50)
by
unknown
11:08
created

MoveModels::__invoke()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 27
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 17
nc 3
nop 3
1
<?php
2
3
namespace Spatie\EloquentSortable;
4
5
class MoveModels
6
{
7
8
    private $orderColumnName;
9
10
    public function __construct($orderColumnName)
11
    {
12
        $this->orderColumnName = $orderColumnName;
13
    }
14
15
    public function __invoke($action, $moved, $displaced)
16
    {
17
        $oldPosition = $moved->{$this->orderColumnName};
18
        $newPosition = $displaced->{$this->orderColumnName};
19
20
        if ($oldPosition === $newPosition) {
21
            return;
22
        }
23
24
        $positionCalculator = new PositionCalculator;
25
        $movedAfter = $action === 'moveAfter';
26
        $movingForward = $oldPosition < $newPosition;
27
        $method = $movingForward ? 'decrement' : 'increment';
28
29
30
        $moved->buildSortQuery()
31
            ->where($this->orderColumnName, '>', min([$oldPosition, $newPosition]))
32
            ->where($this->orderColumnName, '<', max([$oldPosition, $newPosition]))
33
            ->$method($this->orderColumnName);
34
35
36
        $moved->{$this->orderColumnName} = $positionCalculator($movedAfter, $movingForward, $newPosition);
37
        $displaced->{$this->orderColumnName} = $positionCalculator(!$movedAfter, $movingForward, $newPosition);
38
39
        $moved->save();
40
        $displaced->save();
41
    }
42
}
43