Passed
Push — master ( 3e7f2c...6edd16 )
by Jonas
03:28
created

Collection   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 16
c 1
b 0
f 0
dl 0
loc 30
ccs 16
cts 16
cp 1
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A toTree() 0 28 4
1
<?php
2
3
namespace Staudenmeir\LaravelAdjacencyList\Eloquent;
4
5
use Illuminate\Database\Eloquent\Collection as Base;
6
7
class Collection extends Base
8
{
9 12
    public function toTree($childrenRelation = 'children', $parentRelation = 'parent')
10
    {
11 12
        if ($this->isEmpty()) {
12 4
            return $this;
13
        }
14
15 8
        $parentKeyName = $this->first()->getParentKeyName();
16 8
        $localKeyName = $this->first()->getLocalKeyName();
17 8
        $depthName = $this->first()->getDepthName();
18
19 8
        $depths = $this->pluck($depthName);
20
21 8
        $tree = new static(
22 8
            $this->where($depthName, $depths->min())->values()
23
        );
24
25 8
        $itemsByParentKey = $this->groupBy($parentKeyName);
26 8
        $itemsByLocalKey = $this->keyBy($localKeyName);
27
28 8
        foreach ($this->items as $item) {
29 8
            $item->setRelation($childrenRelation, $itemsByParentKey[$item->$localKeyName] ?? new static());
30
31 8
            if (isset($item->$parentKeyName, $itemsByLocalKey[$item->$parentKeyName])) {
32 8
                $item->setRelation($parentRelation, $itemsByLocalKey[$item->$parentKeyName]);
33
            }
34
        }
35
36 8
        return $tree;
37
    }
38
}
39