| Conditions | 4 |
| Paths | 5 |
| Total Lines | 28 |
| Code Lines | 16 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
| 1 | <?php |
||
| 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 | } |
||
| 51 |