Tree::makeFromFlatArray()   A
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 29
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 29
ccs 14
cts 14
cp 1
rs 9.2222
c 0
b 0
f 0
cc 6
nc 6
nop 5
crap 6
1
<?php declare(strict_types=1);
2
3
namespace DCST\Tree;
4
5
class Tree
6
{
7 3
    public static function makeFromFlatArray(
8
        array &$data,
9
        $parentId = 0,
10
        string $key = 'id',
11
        string $parentKey = 'parentId',
12
        string $childKey = 'nodes'
13
    ) {
14 3
        $branch = [];
15
16 3
        foreach ($data as $k => $v) {
17 3
            if (!isset($v[$key])) {
18 1
                throw new \InvalidArgumentException('Invalid identifier key');
19
            }
20
21 2
            if (!isset($v[$parentKey])) {
22 1
                throw new \InvalidArgumentException('Invalid parent key');
23
            }
24
25 1
            if ($v[$parentKey] == $parentId) {
26 1
                $childNodes = static::makeFromFlatArray($data, $v[$key], $key, $parentKey, $childKey);
27 1
                if ($childNodes) {
28 1
                    $v[$childKey] = $childNodes;
29
                }
30 1
                $branch[$v[$key]] = $v;
31 1
                unset($data[$k]);
32
            }
33
        }
34
35 1
        return $branch;
36
    }
37
}
38