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

MoveModels   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
wmc 4
lcom 0
cbo 1
dl 0
loc 38
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B __invoke() 0 27 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