Passed
Push — master ( e6bb40...c8f69f )
by Jonas
03:17 queued 12s
created

Collection   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 17
c 1
b 0
f 0
dl 0
loc 36
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A toTree() 0 28 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
        $parentKeyName = $this->first->relationLoaded('pivot')
28
            ? 'pivot.' . $this->first()->getParentKeyName()
29
            : 'pivot_' . $this->first()->getParentKeyName();
30
        $localKeyName = $this->first()->getLocalKeyName();
31
        $depthName = $this->first()->getDepthName();
32
33
        $depths = $this->pluck($depthName);
34
35
        $graph = new static(
36
            $this->where($depthName, $depths->min())->values()
37
        );
38
39
        $itemsByParentKey = $this->groupBy($parentKeyName);
40
41
        foreach ($this->items as $item) {
42
            $item->setRelation(
43
                $childrenRelation,
44
                $itemsByParentKey[$item->$localKeyName] ?? new static()
45
            );
46
        }
47
48
        return $graph;
49
    }
50
}
51