Collection   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 4
eloc 18
c 2
b 0
f 0
dl 0
loc 40
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A toTree() 0 32 4
1
<?php
2
3
namespace Staudenmeir\LaravelAdjacencyList\Eloquent\Graph;
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
    public function toTree(string $childrenRelation = 'children'): static
22
    {
23
        if ($this->isEmpty()) {
24
            return $this;
25
        }
26
27
        $model = $this->first();
28
29
        $parentKeyName = $model->relationLoaded('pivot')
30
            ? 'pivot.' . $model->getParentKeyName()
31
            : 'pivot_' . $model->getParentKeyName();
32
33
        $localKeyName = $model->getLocalKeyName();
34
35
        $depthName = $model->getDepthName();
36
37
        $depths = $this->pluck($depthName);
38
39
        $graph = new static(
40
            $this->where($depthName, $depths->min())->values()
41
        );
42
43
        $itemsByParentKey = $this->groupBy($parentKeyName);
44
45
        foreach ($this->items as $item) {
46
            $item->setRelation(
47
                $childrenRelation,
48
                $itemsByParentKey[$item->$localKeyName] ?? new static()
49
            );
50
        }
51
52
        return $graph;
53
    }
54
}
55