Completed
Push — master ( 9383fe...482732 )
by ARCANEDEV
08:20
created

TreeHelper::fixNodes()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 15
ccs 9
cts 9
cp 1
rs 9.4285
cc 2
eloc 8
nc 2
nop 1
crap 2
1
<?php namespace Arcanedev\LaravelNestedSet\Utilities;
2
3
use Arcanedev\LaravelNestedSet\Traits\NodeTrait;
4
5
/**
6
 * Class     TreeHelper
7
 *
8
 * @package  Arcanedev\LaravelNestedSet\Utilities
9
 * @author   ARCANEDEV <[email protected]>
10
 */
11
class TreeHelper
12
{
13
    /**
14
     * Fix nodes.
15
     *
16
     * @param  array  $dictionary
17
     *
18
     * @return int
19
     */
20 8
    public static function fixNodes(array &$dictionary)
21
    {
22 8
        $fixed = 0;
23 8
        $cut   = self::reorderNodes($dictionary, $fixed);
24
25
        // Save nodes that have invalid parent as roots
26 8
        while ( ! empty($dictionary)) {
27 4
            $dictionary[null] = reset($dictionary);
28 4
            unset($dictionary[key($dictionary)]);
29
30 4
            $cut = self::reorderNodes($dictionary, $fixed, null, $cut);
31 3
        }
32
33 8
        return $fixed;
34
    }
35
36
    /**
37
     * Reorder nodes.
38
     *
39
     * @param  array     $dictionary
40
     * @param  int       $fixed
41
     * @param  int|null  $parentId
42
     * @param  int       $cut
43
     *
44
     * @return int
45
     */
46 8
    protected static function reorderNodes(
47
        array &$dictionary,
48
        &$fixed,
49
        $parentId = null,
50
        $cut = 1
51
    ) {
52 8
        if ( ! isset($dictionary[$parentId])) {
53 8
            return $cut;
54
        }
55
56
        /** @var NodeTrait $model */
57 8
        foreach ($dictionary[$parentId] as $model) {
58 8
            $lft = $cut;
59 8
            $cut = self::reorderNodes($dictionary, $fixed, $model->getKey(), $cut + 1);
60 8
            $rgt = $cut;
61
62 8
            if ($model->rawNode($lft, $rgt, $parentId)->isDirty()) {
63 8
                $model->save();
64 8
                $fixed++;
65 6
            }
66
67 8
            ++$cut;
68 6
        }
69
70 8
        unset($dictionary[$parentId]);
71
72 8
        return $cut;
73
    }
74
}
75