FieldOrderSetter::updateCurrentFields()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 8
nc 1
nop 1
1
<?php
2
3
namespace Hechoenlaravel\JarvisFoundation\FieldGenerator\Middleware;
4
5
use League\Tactician\Middleware;
6
use Hechoenlaravel\JarvisFoundation\FieldGenerator\FieldModel;
7
8
class FieldOrderSetter 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 (!is_null($command->order)) {
19
            $this->updateCurrentFields($command);
20
        } else {
21
            $command = $this->setOrder($command);
22
        }
23
        return $next($command);
24
    }
25
26
    /**
27
     * If the command has an order, use it and move the ones after that.
28
     * @param $command
29
     */
30
    protected function updateCurrentFields($command)
31
    {
32
        FieldModel::where('entity_id', $command->entity_id)
33
            ->where('order', '>=', $command->order)
34
            ->orderBy('order', 'ASC')
35
            ->get()
36
            ->each(function ($field) {
37
                $field->order = $field->order + 1;
38
                $field->save();
39
            });
40
    }
41
42
    /**
43
     * Set the order for the field
44
     * @param $command
45
     */
46
    protected function setOrder($command)
47
    {
48
        $command->order = 1;
49
        $lastField = FieldModel::where('entity_id', $command->entity_id)->orderBy('order', 'DESC')->first();
50
        if (!is_null($lastField)) {
51
            $command->order = $lastField->order + 1;
52
        }
53
        return $command;
54
    }
55
}
56