Completed
Push — master ( cc8038...edef00 )
by Bartko
01:27
created

Utilities::_flatToNested()   B

Complexity

Conditions 8
Paths 17

Size

Total Lines 36

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 0
Metric Value
dl 0
loc 36
ccs 0
cts 31
cp 0
rs 8.0995
c 0
b 0
f 0
cc 8
nc 17
nop 5
crap 72
1
<?php
2
3
declare(strict_types=1);
4
5
namespace StefanoTree\NestedSet;
6
7
class Utilities
8
{
9
    /**
10
     * Convert flat tree structure to nested.
11
     *
12
     * @param array  $flatTree
13
     * @param string $levelName
14
     *
15
     * @return array
16
     */
17
    public static function flatToNested(
18
        array $flatTree,
19
        string $levelName = 'level'
20
    ): array {
21
        return self::_flatToNested($flatTree, $levelName);
22
    }
23
24
    /**
25
     * @param array    $flatTree
26
     * @param string   $levelName
27
     * @param null|int $level
28
     * @param int      $startPos
29
     * @param array    $result
30
     *
31
     * @return array
32
     */
33
    private static function _flatToNested(
34
        array $flatTree,
35
        string $levelName = 'level',
36
        ?int $level = null,
37
        int $startPos = 0,
38
        array &$result = array()
39
    ): array {
40
        $total = count($flatTree);
41
        $first = true;
42
43
        for ($pos = $startPos; $pos < $total; ++$pos) {
44
            $item = $flatTree[$pos];
45
46
            if (null === $level) {
47
                $level = $item[$levelName];
48
            }
49
50
            if (!array_key_exists('_children', $item)) {
51
                $item['_children'] = array();
52
            }
53
54
            if ($level == $item[$levelName]) {
55
                $result[] = $item;
56
                $first = true;
57
            } elseif (($level + 1) == $item[$levelName] && true == $first) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
58
                $children = array($item);
59
                self::_flatToNested($flatTree, $levelName, (int) $item[$levelName], $pos + 1, $children);
60
                $result[count($result) - 1]['_children'] = $children;
61
                $first = false;
62
            } elseif ($level > $item[$levelName]) {
63
                break;
64
            }
65
        }
66
67
        return $result;
68
    }
69
}
70