Passed
Pull Request — 2.x (#1140)
by
unknown
05:56
created

HasNesting   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 26
c 1
b 0
f 0
dl 0
loc 46
rs 10
wmc 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B saveTreeFromIds() 0 18 7
A flattenTree() 0 19 3
1
<?php
2
3
namespace A17\Twill\Models\Behaviors;
4
5
use Kalnoy\Nestedset\NodeTrait;
6
7
trait HasNesting
8
{
9
    use NodeTrait;
10
11
    public static function saveTreeFromIds($nodeTree)
12
    {
13
        $nodeModels = self::all();
14
        $nodeArrays = self::flattenTree($nodeTree);
15
16
        foreach ($nodeArrays as $nodeArray) {
17
            $nodeModel = $nodeModels->where('id', $nodeArray['id'])->first();
18
19
            if ($nodeArray['parent_id'] === null) {
20
                if (!$nodeModel->isRoot() || $nodeModel->position !== $nodeArray['position']) {
21
                    $nodeModel->position = $nodeArray['position'];
22
                    $nodeModel->saveAsRoot();
23
                }
24
            } else {
25
                if ($nodeModel->position !== $nodeArray['position'] || $nodeModel->parent_id !== $nodeArray['parent_id']) {
26
                    $nodeModel->position = $nodeArray['position'];
27
                    $nodeModel->parent_id = $nodeArray['parent_id'];
28
                    $nodeModel->save();
29
                }
30
            }
31
        }
32
    }
33
34
    public static function flattenTree(array $nodeTree, int $parentId = null)
35
    {
36
        $nodeArrays = [];
37
        $position = 0;
38
39
        foreach ($nodeTree as $node) {
40
            $nodeArrays[] = [
41
                'id' => $node['id'],
42
                'position' => $position++,
43
                'parent_id' => $parentId,
44
            ];
45
46
            if (count($node['children']) > 0) {
47
                $childArrays = self::flattenTree($node['children'], $node['id']);
48
                $nodeArrays = array_merge($nodeArrays, $childArrays);
49
            }
50
        }
51
52
        return $nodeArrays;
53
    }
54
}
55