Collection   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

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

1 Method

Rating   Name   Duplication   Size   Complexity  
A toTree() 0 30 3
1
<?php
2
3
namespace Staudenmeir\LaravelAdjacencyList\Eloquent;
4
5
use Illuminate\Database\Eloquent\Collection as Base;
6
7
/**
8
 * @template TKey of array-key
9
 * @template TModel of \Illuminate\Database\Eloquent\Model
10
 *
11
 * @extends \Illuminate\Database\Eloquent\Collection<TKey, TModel>
12
 */
13
class Collection extends Base
14
{
15
    /**
16
     * Generate a nested tree.
17
     *
18
     * @param string $childrenRelation
19
     * @return static<int, TModel>
20
     */
21 18
    public function toTree($childrenRelation = 'children')
22
    {
23 18
        if ($this->isEmpty()) {
24 6
            return $this;
25
        }
26
27 12
        $model = $this->first();
28 12
29 12
        $parentKeyName = $model->getParentKeyName();
30
31 12
        $localKeyName = $model->getLocalKeyName();
32
33 12
        $depthName = $model->getDepthName();
34 12
35 12
        $depths = $this->pluck($depthName);
36
37 12
        $tree = new static(
38
            $this->where($depthName, $depths->min())->values()
39 12
        );
40 12
41 12
        $itemsByParentKey = $this->groupBy($parentKeyName);
42 12
43 12
        foreach ($this->items as $item) {
44
            $item->setRelation(
45
                $childrenRelation,
46 12
                $itemsByParentKey[$item->$localKeyName] ?? new static()
47
            );
48
        }
49
50
        return $tree;
51
    }
52
}
53