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

MoveModels::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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