SetStepOrder::execute()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 2
1
<?php
2
3
namespace Hechoenlaravel\JarvisFoundation\Flows\Middleware;
4
5
use Hechoenlaravel\JarvisFoundation\Flows\Step;
6
use League\Tactician\Middleware;
7
8
class SetStepOrder implements Middleware
9
{
10
    /**
11
     * @param object $command
12
     * @param callable $next
13
     *
14
     * @return mixed
15
     */
16
    public function execute($command, callable $next)
17
    {
18
        if ($command->order === null) {
19
            $this->setOrder($command);
20
        } else {
21
            $this->reOrderSteps($command);
22
        }
23
        return $next($command);
24
    }
25
26
    /**
27
     * @param $command
28
     */
29
    private function reOrderSteps($command)
30
    {
31
        Step::where('flow_id', $command->flow->id)
32
            ->where('order', '>=', $command->order)
33
            ->orderBy('order', 'ASC')
34
            ->get()
35
            ->each(function ($step) {
36
                $step->order = $step->order + 1;
37
                $step->save();
38
            });
39
    }
40
41
    /**
42
     * @param $command
43
     */
44
    private function setOrder($command)
45
    {
46
        $command->order = 1;
47
        $lastStep = Step::where('flow_id', $command->flow->id)->orderBy('order', 'asc')->first();
48
        if ($lastStep) {
49
            $command->order = $lastStep->order + 1;
50
        }
51
    }
52
}
53