Repository navigation
Expand file tree
/
Copy pathTreeCollection.php
More file actions
102 lines (89 loc) · 2.87 KB
/
Copy pathTreeCollection.php
File metadata and controls
102 lines (89 loc) · 2.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php namespace October\Rain\Database;
/**
* Custom collection used by NestedTree trait.
*
* General access methods:
*
* $collection->toNested(); // Converts collection to an eager loaded one.
*
*/
class TreeCollection extends Collection
{
/**
* Converts a flat collection of nested set models to an set where
* children is eager loaded
* @param bool $removeOrphans Remove nodes that exist without their parents.
* @return \October\Rain\Database\Collection
*/
public function toNested($removeOrphans = true)
{
/*
* Set new collection for "children" relations
*/
$collection = $this->getDictionary();
foreach ($collection as $key => $model) {
$model->setRelation('children', new Collection);
}
/*
* Assign all child nodes to their parents
*/
$nestedKeys = [];
foreach ($collection as $key => $model) {
if (!$parentKey = $model->getParentId())
continue;
if (array_key_exists($parentKey, $collection)) {
$collection[$parentKey]->children[] = $model;
$nestedKeys[] = $model->getKey();
}
elseif ($removeOrphans) {
$nestedKeys[] = $model->getKey();
}
}
/*
* Remove processed nodes
*/
foreach ($nestedKeys as $key) {
unset($collection[$key]);
}
return new Collection($collection);
}
/**
* Gets an array with values of a given column. Values are indented according to their depth.
* @param string $value Array values
* @param string $key Array keys
* @param string $indent Character to indent depth
* @return array
*/
public function listsNested($value, $key = null, $indent = ' ')
{
/*
* Recursive helper function
*/
$buildCollection = function($items, $depth = 0) use (&$buildCollection, $value, $key, $indent) {
$result = [];
$indentString = str_repeat($indent, $depth);
foreach ($items as $item) {
if ($key !== null) {
$result[$item->{$key}] = $indentString . $item->{$value};
}
else {
$result[] = $indentString . $item->{$value};
}
/*
* Add the children
*/
$childItems = $item->getChildren();
if ($childItems->count() > 0) {
$result = $result + $buildCollection($childItems, $depth + 1);
}
}
return $result;
};
/*
* Build a nested collection
*/
$rootItems = $this->toNested();
$result = $buildCollection($rootItems);
return $result;
}
}