@@ -77,7 +77,7 @@ public function toTree($root = false)
77
77
*
78
78
* @return int
79
79
*/
80
- protected function getRootNodeId ($ root )
80
+ protected function getRootNodeId ($ root = false )
81
81
{
82
82
if (NestedSet::isNode ($ root )) {
83
83
return $ root ->getKey ();
@@ -106,44 +106,38 @@ protected function getRootNodeId($root)
106
106
* Build a list of nodes that retain the order that they were pulled from
107
107
* the database.
108
108
*
109
- * @return Collection|static
109
+ * @param bool $root
110
+ *
111
+ * @return static
110
112
*/
111
- public function toFlattenedTree ( )
113
+ public function toFlatTree ( $ root = false )
112
114
{
113
- $ tree = $ this -> toTree () ;
115
+ $ result = new static ;
114
116
115
- return $ tree ->flattenTree ();
116
- }
117
+ if ($ this ->isEmpty ()) return $ result ;
117
118
118
- /**
119
- * Flatten a tree into a non recursive array
120
- */
121
- public function flattenTree ()
122
- {
123
- $ items = [];
124
-
125
- foreach ($ this ->items as $ node ) {
126
- $ items = array_merge ($ items , $ this ->flattenNode ($ node ));
127
- }
119
+ $ groupedNodes = $ this ->groupBy ($ this ->first ()->getParentIdName ());
128
120
129
- return new static ( $ items );
121
+ return $ result -> flattenTree ( $ groupedNodes , $ this -> getRootNodeId ( $ root ) );
130
122
}
131
123
132
124
/**
133
- * Flatten a single node
125
+ * Flatten a tree into a non recursive array.
126
+ *
127
+ * @param Collection $groupedNodes
128
+ * @param mixed $parentId
134
129
*
135
- * @param $node
136
- * @return array
130
+ * @return $this
137
131
*/
138
- protected function flattenNode ( $ node )
132
+ protected function flattenTree ( self $ groupedNodes , $ parentId )
139
133
{
140
- $ items = [];
141
- $ items [] = $ node ;
134
+ foreach ( $ groupedNodes -> get ( $ parentId , []) as $ node ) {
135
+ $ this -> push ( $ node) ;
142
136
143
- foreach ($ node ->children as $ childNode ) {
144
- $ items = array_merge ($ items , $ this ->flattenNode ($ childNode ));
137
+ $ this ->flattenTree ($ groupedNodes , $ node ->getKey ());
145
138
}
146
139
147
- return $ items ;
140
+ return $ this ;
148
141
}
142
+
149
143
}
0 commit comments