Collection   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 37
rs 10
wmc 8

2 Methods

Rating   Name   Duplication   Size   Complexity  
A toHierarchy() 0 10 2
A hierarchical() 0 23 6
1
<?php
2
3
namespace Encima\Albero\Extensions\Eloquent;
4
5
use Illuminate\Database\Eloquent\Collection as BaseCollection;
6
7
class Collection extends BaseCollection
8
{
9
    public function toHierarchy(): BaseCollection
10
    {
11
        $dict = $this->getDictionary();
12
13
        // Enforce sorting by $orderColumn setting in Baum\Node instance
14
        uasort($dict, function ($a, $b) {
15
            return ($a->getOrder() >= $b->getOrder()) ? 1 : -1;
16
        });
17
18
        return new BaseCollection($this->hierarchical($dict));
19
    }
20
21
    protected function hierarchical(array $result): array
22
    {
23
        foreach ($result as $key => $node) {
24
            $node->setRelation('children', new BaseCollection());
25
        }
26
27
        $nestedKeys = [];
28
29
        foreach ($result as $key => $node) {
30
            $parentKey = $node->getParentId();
31
32
            if (!is_null($parentKey) && array_key_exists($parentKey, $result)) {
33
                $result[$parentKey]->children[] = $node;
34
35
                $nestedKeys[] = $node->getKey();
36
            }
37
        }
38
39
        foreach ($nestedKeys as $key) {
40
            unset($result[$key]);
41
        }
42
43
        return $result;
44
    }
45
}
46