forked from octobercms/library
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleTree.php
More file actions
279 lines (245 loc) · 7.41 KB
/
SimpleTree.php
File metadata and controls
279 lines (245 loc) · 7.41 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
<?php namespace October\Rain\Database\Traits;
use Illuminate\Support\Arr;
use October\Rain\Database\Collection;
use October\Rain\Database\TreeCollection;
use Exception;
/**
* SimpleTree model trait
*
* Simple tree implementation, for advanced implementation see:
* October\Rain\Database\Traits\NestedTree
*
* SimpleTree is the bare minimum needed for tree functionality, the
* methods defined here should be implemented by all "tree" traits.
*
* Usage:
*
* Model table must have parent_id table column.
* In the model class definition:
*
* use \October\Rain\Database\Traits\SimpleTree;
*
* General access methods:
*
* $model->getChildren(); // Returns children of this node
* $model->getChildCount(); // Returns number of all children.
* $model->getAllChildren(); // Returns all children of this node
* $model->getAllRoot(); // Returns all root level nodes (eager loaded)
* $model->getAll(); // Returns everything in correct order.
*
* Query builder methods:
*
* $query->listsNested(); // Returns an indented array of key and value columns.
*
* You can change the sort field used by declaring:
*
* const PARENT_ID = 'my_parent_column';
*
* @package october\database
* @author Alexey Bobkov, Samuel Georges
*/
trait SimpleTree
{
/**
* initializeSimpleTree constructor
*/
public function initializeSimpleTree()
{
// Define relationships
$this->hasMany['children'] = [
static::class,
'key' => $this->getParentColumnName(),
'replicate' => false
];
$this->belongsTo['parent'] = [
static::class,
'key' => $this->getParentColumnName(),
'replicate' => false
];
// Multisite
if (
$this->isClassInstanceOf(\October\Contracts\Database\MultisiteInterface::class) &&
$this->isMultisiteSyncEnabled() &&
$this->getMultisiteConfig('structure', true)
) {
$this->addPropagatable(['children', 'parent']);
}
}
/**
* getAll returns all nodes and children.
* @return \October\Rain\Database\Collection
*/
public function getAll()
{
$collection = [];
foreach ($this->getAllRoot() as $rootNode) {
$collection[] = $rootNode;
$collection = $collection + $rootNode->getAllChildren()->getDictionary();
}
return new Collection($collection);
}
/**
* getAllChildren gets a list of children records, with their children (recursive)
* @return \October\Rain\Database\Collection
*/
public function getAllChildren()
{
$result = [];
$children = $this->getChildren();
foreach ($children as $child) {
$result[] = $child;
$childResult = $child->getAllChildren();
foreach ($childResult as $subChild) {
$result[] = $subChild;
}
}
return new Collection($result);
}
/**
* getChildren returns direct child nodes.
* @return \October\Rain\Database\Collection
*/
public function getChildren()
{
return $this->children;
}
/**
* getChildCount returns number of all children below it.
* @return int
*/
public function getChildCount()
{
return count($this->getAllChildren());
}
/**
* getParents returns an array of parents, this is a heavy query and can produce
* in multiple queries.
*/
public function getParents()
{
$result = [];
$parent = $this;
$result[] = $parent;
while ($parent = $parent->parent) {
$result[] = $parent;
}
return array_reverse($result);
}
//
// Scopes
//
/**
* scopeGetAllRoot returns a list of all root nodes, without eager loading.
* @return \October\Rain\Database\Collection
*/
public function scopeGetAllRoot($query)
{
return $query->where($this->getParentColumnName(), null)->get();
}
/**
* scopeGetNested is a non-chaining scope, returns an eager loaded hierarchy tree.
* Children are eager loaded inside the $model->children relation.
* @return Collection A collection
*/
public function scopeGetNested($query)
{
return $query->get()->toNested();
}
/**
* scopeListsNested gets an array with values of a given column. Values are indented
* according to their depth.
* @param string $column Array values
* @param string $key Array keys
* @param string $indent Character to indent depth
* @return array
*/
public function scopeListsNested($query, $column, $key = null, $indent = ' ')
{
$idName = $this->getKeyName();
$parentName = $this->getParentColumnName();
$columns = [$idName, $parentName, $column];
if ($key !== null) {
$columns[] = $key;
}
$collection = $query->getQuery()->get($columns);
// Assign all child nodes to their parents
$pairMap = [];
$rootItems = [];
foreach ($collection as $record) {
if ($parentId = $record->{$parentName}) {
if (!isset($pairMap[$parentId])) {
$pairMap[$parentId] = [];
}
$pairMap[$parentId][] = $record;
}
else {
$rootItems[] = $record;
}
}
// Recursive helper function
$buildCollection = function(
$items,
$map,
$depth = 0
) use (
&$buildCollection,
$column,
$key,
$indent,
$idName
) {
$result = [];
$indentString = str_repeat($indent, $depth);
foreach ($items as $item) {
if (!property_exists($item, $column)) {
throw new Exception('Column mismatch in listsNested method. Are you sure the columns exist?');
}
if ($key !== null) {
$result[$item->{$key}] = $indentString . $item->{$column};
}
else {
$result[] = $indentString . $item->{$column};
}
// Add the children
$childItems = Arr::get($map, $item->{$idName}, []);
if (count($childItems) > 0) {
$result = $result + $buildCollection($childItems, $map, $depth + 1);
}
}
return $result;
};
// Build a nested collection
return $buildCollection($rootItems, $pairMap);
}
/**
* getParentColumnName
* @return string
*/
public function getParentColumnName()
{
return defined('static::PARENT_ID') ? static::PARENT_ID : 'parent_id';
}
/**
* getQualifiedParentColumnName
* @return string
*/
public function getQualifiedParentColumnName()
{
return $this->getTable(). '.' .$this->getParentColumnName();
}
/**
* getParentId gets value of the model parent_id column.
* @return int
*/
public function getParentId()
{
return $this->getAttribute($this->getParentColumnName());
}
/**
* newCollection returns a custom TreeCollection collection.
*/
public function newCollection(array $models = [])
{
return new TreeCollection($models);
}
}