| Conditions | 4 |
| Paths | 4 |
| Total Lines | 28 |
| Code Lines | 15 |
| Lines | 0 |
| Ratio | 0 % |
| Tests | 16 |
| CRAP Score | 4 |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
| 1 | <?php |
||
| 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 | } |
||
| 39 |