SetStepOrder   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 0
dl 0
loc 45
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A execute() 0 9 2
A reOrderSteps() 0 11 1
A setOrder() 0 8 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