Completed
Pull Request — master (#5574)
by Christopher
11:14
created

Hierarchy::liveChildren()   C

Complexity

Conditions 8
Paths 9

Size

Total Lines 25
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 2
Metric Value
cc 8
eloc 18
nc 9
nop 2
dl 0
loc 25
rs 5.3846
c 2
b 1
f 2
1
<?php
2
/**
3
 * DataObjects that use the Hierarchy extension can be be organised as a hierarchy, with children and parents. The most
4
 * obvious example of this is SiteTree.
5
 *
6
 * @package framework
7
 * @subpackage model
8
 *
9
 * @property int        ParentID
10
 * @property DataObject owner
11
 * @method   DataObject Parent
12
 */
13
class Hierarchy extends DataExtension {
14
15
	protected $markedNodes;
16
17
	protected $markingFilter;
18
19
	/** @var int */
20
	protected $_cache_numChildren;
21
22
	/**
23
	 * The lower bounds for the amount of nodes to mark. If set, the logic will expand nodes until it reaches at least
24
	 * this number, and then stops. Root nodes will always show regardless of this settting. Further nodes can be
25
	 * lazy-loaded via ajax. This isn't a hard limit. Example: On a value of 10, with 20 root nodes, each having 30
26
	 * children, the actual node count will be 50 (all root nodes plus first expanded child).
27
	 *
28
	 * @config
29
	 * @var int
30
	 */
31
	private static $node_threshold_total = 50;
32
33
	/**
34
	 * Limit on the maximum children a specific node can display. Serves as a hard limit to avoid exceeding available
35
	 * server resources in generating the tree, and browser resources in rendering it. Nodes with children exceeding
36
	 * this value typically won't display any children, although this is configurable through the $nodeCountCallback
37
	 * parameter in {@link getChildrenAsUL()}. "Root" nodes will always show all children, regardless of this setting.
38
	 *
39
	 * @config
40
	 * @var int
41
	 */
42
	private static $node_threshold_leaf = 250;
43
44
	/**
45
	 * A list of classnames to exclude from display in both the CMS and front end
46
	 * displays. ->Children() and ->AllChildren affected.
47
	 * Especially useful for big sets of pages like listings
48
	 * If you use this, and still need the classes to be editable
49
	 * then add a model admin for the class
50
	 * Note: Does not filter subclasses (non-inheriting)
51
	 *
52
	 * @var array
53
	 * @config
54
	 */
55
	private static $hide_from_hierarchy = array();
56
57
	/**
58
	 * A list of classnames to exclude from display in the page tree views of the CMS,
59
	 * unlike $hide_from_hierarchy above which effects both CMS and front end.
60
	 * Especially useful for big sets of pages like listings
61
	 * If you use this, and still need the classes to be editable
62
	 * then add a model admin for the class
63
	 * Note: Does not filter subclasses (non-inheriting)
64
	 *
65
	 * @var array
66
	 * @config
67
	 */
68
	private static $hide_from_cms_tree = array();
69
70
	public static function get_extra_config($class, $extension, $args) {
0 ignored issues
show
Unused Code introduced by
The parameter $extension is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
71
		return array(
72
			'has_one' => array('Parent' => $class)
73
		);
74
	}
75
76
	/**
77
	 * Validate the owner object - check for existence of infinite loops.
78
	 *
79
	 * @param ValidationResult $validationResult
80
	 */
81
	public function validate(ValidationResult $validationResult) {
82
		// The object is new, won't be looping.
83
		if (!$this->owner->ID) return;
84
		// The object has no parent, won't be looping.
85
		if (!$this->owner->ParentID) return;
86
		// The parent has not changed, skip the check for performance reasons.
87
		if (!$this->owner->isChanged('ParentID')) return;
88
89
		// Walk the hierarchy upwards until we reach the top, or until we reach the originating node again.
90
		$node = $this->owner;
91
		while($node) {
92
			if ($node->ParentID==$this->owner->ID) {
93
				// Hierarchy is looping.
94
				$validationResult->error(
95
					_t(
96
						'Hierarchy.InfiniteLoopNotAllowed',
97
						'Infinite loop found within the "{type}" hierarchy. Please change the parent to resolve this',
98
						'First argument is the class that makes up the hierarchy.',
99
						array('type' => $this->owner->class)
100
					),
101
					'INFINITE_LOOP'
102
				);
103
				break;
104
			}
105
			$node = $node->ParentID ? $node->Parent() : null;
106
		}
107
108
		// At this point the $validationResult contains the response.
109
	}
110
111
	/**
112
	 * Returns the children of this DataObject as an XHTML UL. This will be called recursively on each child, so if they
113
	 * have children they will be displayed as a UL inside a LI.
114
	 *
115
	 * @param string          $attributes         Attributes to add to the UL
116
	 * @param string|callable $titleEval          PHP code to evaluate to start each child - this should include '<li>'
117
	 * @param string          $extraArg           Extra arguments that will be passed on to children, for if they
118
	 *                                            overload this function
119
	 * @param bool            $limitToMarked      Display only marked children
120
	 * @param string          $childrenMethod     The name of the method used to get children from each object
121
	 * @param bool            $rootCall           Set to true for this first call, and then to false for calls inside
122
	 *                                            the recursion. You should not change this.
123
	 * @param int             $nodeCountThreshold See {@link self::$node_threshold_total}
124
	 * @param callable        $nodeCountCallback  Called with the node count, which gives the callback an opportunity to
125
	 *                                            intercept the query. Useful e.g. to avoid excessive children listings
126
	 *                                            (Arguments: $parent, $numChildren)
127
	 *
128
	 * @return string
129
	 */
130
	public function getChildrenAsUL($attributes = "", $titleEval = '"<li>" . $child->Title', $extraArg = null,
131
			$limitToMarked = false, $childrenMethod = "AllChildrenIncludingDeleted",
132
			$numChildrenMethod = "numChildren", $rootCall = true,
133
			$nodeCountThreshold = null, $nodeCountCallback = null) {
134
135
		if(!is_numeric($nodeCountThreshold)) {
136
			$nodeCountThreshold = Config::inst()->get('Hierarchy', 'node_threshold_total');
137
		}
138
139
		if($limitToMarked && $rootCall) {
140
			$this->markingFinished($numChildrenMethod);
141
		}
142
143
144
		if($nodeCountCallback) {
145
			$nodeCountWarning = $nodeCountCallback($this->owner, $this->owner->$numChildrenMethod());
146
			if($nodeCountWarning) return $nodeCountWarning;
147
		}
148
149
150
		if($this->owner->hasMethod($childrenMethod)) {
151
			$children = $this->owner->$childrenMethod($extraArg);
152
		} else {
153
			user_error(sprintf("Can't find the method '%s' on class '%s' for getting tree children",
154
				$childrenMethod, get_class($this->owner)), E_USER_ERROR);
155
		}
156
157
		if($children) {
158
159
			if($attributes) {
160
				$attributes = " $attributes";
161
			}
162
163
			$output = "<ul$attributes>\n";
164
165
			foreach($children as $child) {
0 ignored issues
show
Bug introduced by
The variable $children does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
166
				if(!$limitToMarked || $child->isMarked()) {
167
					$foundAChild = true;
168
					if(is_callable($titleEval)) {
169
						$output .= $titleEval($child, $numChildrenMethod);
170
					} else {
171
						$output .= eval("return $titleEval;");
0 ignored issues
show
Coding Style introduced by
It is generally not recommended to use eval unless absolutely required.

On one hand, eval might be exploited by malicious users if they somehow manage to inject dynamic content. On the other hand, with the emergence of faster PHP runtimes like the HHVM, eval prevents some optimization that they perform.

Loading history...
172
					}
173
					$output .= "\n";
174
175
					$numChildren = $child->$numChildrenMethod();
176
177
					if(
178
						// Always traverse into opened nodes (they might be exposed as parents of search results)
179
						$child->isExpanded()
180
						// Only traverse into children if we haven't reached the maximum node count already.
181
						// Otherwise, the remaining nodes are lazy loaded via ajax.
182
						&& $child->isMarked()
183
					) {
184
						// Additionally check if node count requirements are met
185
						$nodeCountWarning = $nodeCountCallback ? $nodeCountCallback($child, $numChildren) : null;
186
						if($nodeCountWarning) {
187
							$output .= $nodeCountWarning;
188
							$child->markClosed();
189
						} else {
190
							$output .= $child->getChildrenAsUL("", $titleEval, $extraArg, $limitToMarked,
191
								$childrenMethod,	$numChildrenMethod, false, $nodeCountThreshold);
192
						}
193
					} elseif($child->isTreeOpened()) {
194
						// Since we're not loading children, don't mark it as open either
195
						$child->markClosed();
196
					}
197
					$output .= "</li>\n";
198
				}
199
			}
200
201
			$output .= "</ul>\n";
202
		}
203
204
		if(isset($foundAChild) && $foundAChild) {
205
			return $output;
0 ignored issues
show
Bug introduced by
The variable $output does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
206
		}
207
	}
208
209
	/**
210
	 * Mark a segment of the tree, by calling mark().
211
	 *
212
	 * The method performs a breadth-first traversal until the number of nodes is more than minCount. This is used to
213
	 * get a limited number of tree nodes to show in the CMS initially.
214
	 *
215
	 * This method returns the number of nodes marked.  After this method is called other methods can check
216
	 * {@link isExpanded()} and {@link isMarked()} on individual nodes.
217
	 *
218
	 * @param int $nodeCountThreshold See {@link getChildrenAsUL()}
219
	 * @return int The actual number of nodes marked.
220
	 */
221
	public function markPartialTree($nodeCountThreshold = 30, $context = null,
222
			$childrenMethod = "AllChildrenIncludingDeleted", $numChildrenMethod = "numChildren") {
223
224
		if(!is_numeric($nodeCountThreshold)) $nodeCountThreshold = 30;
225
226
		$this->markedNodes = array($this->owner->ID => $this->owner);
227
		$this->owner->markUnexpanded();
228
229
		// foreach can't handle an ever-growing $nodes list
230
		while(list($id, $node) = each($this->markedNodes)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $id is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
231
			$children = $this->markChildren($node, $context, $childrenMethod, $numChildrenMethod);
232
			if($nodeCountThreshold && sizeof($this->markedNodes) > $nodeCountThreshold) {
233
				// Undo marking children as opened since they're lazy loaded
234
				if($children) foreach($children as $child) $child->markClosed();
235
				break;
236
			}
237
		}
238
		return sizeof($this->markedNodes);
239
	}
240
241
	/**
242
	 * Filter the marking to only those object with $node->$parameterName == $parameterValue
243
	 *
244
	 * @param string $parameterName  The parameter on each node to check when marking.
245
	 * @param mixed  $parameterValue The value the parameter must be to be marked.
246
	 */
247
	public function setMarkingFilter($parameterName, $parameterValue) {
248
		$this->markingFilter = array(
249
			"parameter" => $parameterName,
250
			"value" => $parameterValue
251
		);
252
	}
253
254
	/**
255
	 * Filter the marking to only those where the function returns true. The node in question will be passed to the
256
	 * function.
257
	 *
258
	 * @param string $funcName The name of the function to call
259
	 */
260
	public function setMarkingFilterFunction($funcName) {
261
		$this->markingFilter = array(
262
			"func" => $funcName,
263
		);
264
	}
265
266
	/**
267
	 * Returns true if the marking filter matches on the given node.
268
	 *
269
	 * @param DataObject $node Node to check
270
	 * @return bool
271
	 */
272
	public function markingFilterMatches($node) {
273
		if(!$this->markingFilter) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->markingFilter of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
274
			return true;
275
		}
276
277
		if(isset($this->markingFilter['parameter']) && $parameterName = $this->markingFilter['parameter']) {
278
			if(is_array($this->markingFilter['value'])){
279
				$ret = false;
280
				foreach($this->markingFilter['value'] as $value) {
281
					$ret = $ret||$node->$parameterName==$value;
282
					if($ret == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
283
						break;
284
					}
285
				}
286
				return $ret;
287
			} else {
288
				return ($node->$parameterName == $this->markingFilter['value']);
289
			}
290
		} else if ($func = $this->markingFilter['func']) {
291
			return call_user_func($func, $node);
292
		}
293
	}
294
295
	/**
296
	 * Mark all children of the given node that match the marking filter.
297
	 *
298
	 * @param DataObject $node              Parent node
299
	 * @param mixed      $context
300
	 * @param string     $childrenMethod    The name of the instance method to call to get the object's list of children
301
	 * @param string     $numChildrenMethod The name of the instance method to call to count the object's children
302
	 * @return DataList
303
	 */
304
	public function markChildren($node, $context = null, $childrenMethod = "AllChildrenIncludingDeleted",
305
			$numChildrenMethod = "numChildren") {
306
		if($node->hasMethod($childrenMethod)) {
307
			$children = $node->$childrenMethod($context);
308
		} else {
309
			user_error(sprintf("Can't find the method '%s' on class '%s' for getting tree children",
310
				$childrenMethod, get_class($node)), E_USER_ERROR);
311
		}
312
313
		$node->markExpanded();
314
		if($children) {
315
			foreach($children as $child) {
0 ignored issues
show
Bug introduced by
The variable $children does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
316
				$markingMatches = $this->markingFilterMatches($child);
317
				if($markingMatches) {
318
					if($child->$numChildrenMethod()) {
319
						$child->markUnexpanded();
320
					} else {
321
						$child->markExpanded();
322
					}
323
					$this->markedNodes[$child->ID] = $child;
324
				}
325
			}
326
		}
327
328
		return $children;
329
	}
330
331
	/**
332
	 * Ensure marked nodes that have children are also marked expanded. Call this after marking but before iterating
333
	 * over the tree.
334
	 *
335
	 * @param string $numChildrenMethod The name of the instance method to call to count the object's children
336
	 */
337
	protected function markingFinished($numChildrenMethod = "numChildren") {
338
		// Mark childless nodes as expanded.
339
		if($this->markedNodes) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->markedNodes of type DataObject[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
340
			foreach($this->markedNodes as $id => $node) {
341
				if(!$node->isExpanded() && !$node->$numChildrenMethod()) {
342
					$node->markExpanded();
343
				}
344
			}
345
		}
346
	}
347
348
	/**
349
	 * Return CSS classes of 'unexpanded', 'closed', both, or neither, as well as a 'jstree-*' state depending on the
350
	 * marking of this DataObject.
351
	 *
352
	 * @param string $numChildrenMethod The name of the instance method to call to count the object's children
353
	 * @return string
354
	 */
355
	public function markingClasses($numChildrenMethod="numChildren") {
356
		$classes = '';
357
		if(!$this->isExpanded()) {
358
			$classes .= " unexpanded";
359
		}
360
361
		// Set jstree open state, or mark it as a leaf (closed) if there are no children
362
		if(!$this->owner->$numChildrenMethod()) {
363
			$classes .= " jstree-leaf closed";
364
		} elseif($this->isTreeOpened()) {
365
			$classes .= " jstree-open";
366
		} else {
367
			$classes .= " jstree-closed closed";
368
		}
369
		return $classes;
370
	}
371
372
	/**
373
	 * Mark the children of the DataObject with the given ID.
374
	 *
375
	 * @param int  $id   ID of parent node
376
	 * @param bool $open If this is true, mark the parent node as opened
377
	 * @return bool
378
	 */
379
	public function markById($id, $open = false) {
380
		if(isset($this->markedNodes[$id])) {
381
			$this->markChildren($this->markedNodes[$id]);
382
			if($open) {
383
				$this->markedNodes[$id]->markOpened();
384
			}
385
			return true;
386
		} else {
387
			return false;
388
		}
389
	}
390
391
	/**
392
	 * Expose the given object in the tree, by marking this page and all it ancestors.
393
	 *
394
	 * @param DataObject $childObj
395
	 */
396
	public function markToExpose($childObj) {
397
		if(is_object($childObj)){
398
			$stack = array_reverse($childObj->parentStack());
399
			foreach($stack as $stackItem) {
400
				$this->markById($stackItem->ID, true);
401
			}
402
		}
403
	}
404
405
	/**
406
	 * Return the IDs of all the marked nodes.
407
	 *
408
	 * @return array
409
	 */
410
	public function markedNodeIDs() {
411
		return array_keys($this->markedNodes);
412
	}
413
414
	/**
415
	 * Return an array of this page and its ancestors, ordered item -> root.
416
	 *
417
	 * @return SiteTree[]
418
	 */
419
	public function parentStack() {
420
		$p = $this->owner;
421
422
		while($p) {
423
			$stack[] = $p;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$stack was never initialized. Although not strictly required by PHP, it is generally a good practice to add $stack = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
424
			$p = $p->ParentID ? $p->Parent() : null;
425
		}
426
427
		return $stack;
0 ignored issues
show
Bug introduced by
The variable $stack does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
428
	}
429
430
	/**
431
	 * Cache of DataObjects' marked statuses: [ClassName][ID] = bool
432
	 * @var array
433
	 */
434
	protected static $marked = array();
435
436
	/**
437
	 * Cache of DataObjects' expanded statuses: [ClassName][ID] = bool
438
	 * @var array
439
	 */
440
	protected static $expanded = array();
441
442
	/**
443
	 * Cache of DataObjects' opened statuses: [ClassName][ID] = bool
444
	 * @var array
445
	 */
446
	protected static $treeOpened = array();
447
448
	/**
449
	 * Mark this DataObject as expanded.
450
	 */
451
	public function markExpanded() {
452
		self::$marked[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID] = true;
453
		self::$expanded[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID] = true;
454
	}
455
456
	/**
457
	 * Mark this DataObject as unexpanded.
458
	 */
459
	public function markUnexpanded() {
460
		self::$marked[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID] = true;
461
		self::$expanded[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID] = false;
462
	}
463
464
	/**
465
	 * Mark this DataObject's tree as opened.
466
	 */
467
	public function markOpened() {
468
		self::$marked[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID] = true;
469
		self::$treeOpened[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID] = true;
470
	}
471
472
	/**
473
	 * Mark this DataObject's tree as closed.
474
	 */
475
	public function markClosed() {
476
		if(isset(self::$treeOpened[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID])) {
477
			unset(self::$treeOpened[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID]);
478
		}
479
	}
480
481
	/**
482
	 * Check if this DataObject is marked.
483
	 *
484
	 * @return bool
485
	 */
486
	public function isMarked() {
487
		$baseClass = ClassInfo::baseDataClass($this->owner->class);
488
		$id = $this->owner->ID;
489
		return isset(self::$marked[$baseClass][$id]) ? self::$marked[$baseClass][$id] : false;
490
	}
491
492
	/**
493
	 * Check if this DataObject is expanded.
494
	 *
495
	 * @return bool
496
	 */
497
	public function isExpanded() {
498
		$baseClass = ClassInfo::baseDataClass($this->owner->class);
499
		$id = $this->owner->ID;
500
		return isset(self::$expanded[$baseClass][$id]) ? self::$expanded[$baseClass][$id] : false;
501
	}
502
503
	/**
504
	 * Check if this DataObject's tree is opened.
505
	 *
506
	 * @return bool
507
	 */
508
	public function isTreeOpened() {
509
		$baseClass = ClassInfo::baseDataClass($this->owner->class);
510
		$id = $this->owner->ID;
511
		return isset(self::$treeOpened[$baseClass][$id]) ? self::$treeOpened[$baseClass][$id] : false;
512
	}
513
514
	/**
515
	 * Get a list of this DataObject's and all it's descendants IDs.
516
	 *
517
	 * @return int[]
518
	 */
519
	public function getDescendantIDList() {
520
		$idList = array();
521
		$this->loadDescendantIDListInto($idList);
522
		return $idList;
523
	}
524
525
	/**
526
	 * Get a list of this DataObject's and all it's descendants ID, and put them in $idList.
527
	 *
528
	 * @param array $idList Array to put results in.
529
	 */
530
	public function loadDescendantIDListInto(&$idList) {
531
		if($children = $this->AllChildren()) {
532
			foreach($children as $child) {
533
				if(in_array($child->ID, $idList)) {
534
					continue;
535
				}
536
				$idList[] = $child->ID;
537
				$ext = $child->getExtensionInstance('Hierarchy');
538
				$ext->setOwner($child);
539
				$ext->loadDescendantIDListInto($idList);
540
				$ext->clearOwner();
541
			}
542
		}
543
	}
544
545
	/**
546
	 * Get the children for this DataObject.
547
	 *
548
	 * @return DataList
549
	 */
550
	public function Children() {
551
		if(!(isset($this->_cache_children) && $this->_cache_children)) {
552
			$result = $this->owner->stageChildren(false);
553
			$children = array();
554
			foreach ($result as $record) {
555
				if ($record->canView()) {
556
					$children[] = $record;
557
				}
558
			}
559
			$this->_cache_children = new ArrayList($children);
0 ignored issues
show
Bug introduced by
The property _cache_children does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
560
		}
561
		return $this->_cache_children;
562
	}
563
564
	/**
565
	 * Return all children, including those 'not in menus'.
566
	 *
567
	 * @return DataList
568
	 */
569
	public function AllChildren() {
570
		return $this->owner->stageChildren(true);
571
	}
572
573
	/**
574
	 * Return all children, including those that have been deleted but are still in live.
575
	 * - Deleted children will be marked as "DeletedFromStage"
576
	 * - Added children will be marked as "AddedToStage"
577
	 * - Modified children will be marked as "ModifiedOnStage"
578
	 * - Everything else has "SameOnStage" set, as an indicator that this information has been looked up.
579
	 *
580
	 * @param mixed $context
581
	 * @return ArrayList
582
	 */
583
	public function AllChildrenIncludingDeleted($context = null) {
584
		return $this->doAllChildrenIncludingDeleted($context);
585
	}
586
587
	/**
588
	 * @see AllChildrenIncludingDeleted
589
	 *
590
	 * @param mixed $context
591
	 * @return ArrayList
592
	 */
593
	public function doAllChildrenIncludingDeleted($context = null) {
594
		if(!$this->owner) user_error('Hierarchy::doAllChildrenIncludingDeleted() called without $this->owner');
595
596
		$baseClass = ClassInfo::baseDataClass($this->owner->class);
597
		if($baseClass) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $baseClass of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
598
			$stageChildren = $this->owner->stageChildren(true);
599
600
			// Add live site content that doesn't exist on the stage site, if required.
601
			if($this->owner->hasExtension('Versioned')) {
602
				// Next, go through the live children.  Only some of these will be listed
603
				$liveChildren = $this->owner->liveChildren(true, true);
604
				if($liveChildren) {
605
					$merged = new ArrayList();
606
					$merged->merge($stageChildren);
607
					$merged->merge($liveChildren);
608
					$stageChildren = $merged;
609
				}
610
			}
611
612
			$this->owner->extend("augmentAllChildrenIncludingDeleted", $stageChildren, $context);
613
614
		} else {
615
			user_error("Hierarchy::AllChildren() Couldn't determine base class for '{$this->owner->class}'",
616
				E_USER_ERROR);
617
		}
618
619
		return $stageChildren;
0 ignored issues
show
Bug introduced by
The variable $stageChildren does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
620
	}
621
622
	/**
623
	 * Return all the children that this page had, including pages that were deleted from both stage & live.
624
	 *
625
	 * @return DataList
626
	 * @throws Exception
627
	 */
628
	public function AllHistoricalChildren() {
629
		if(!$this->owner->hasExtension('Versioned')) {
630
			throw new Exception('Hierarchy->AllHistoricalChildren() only works with Versioned extension applied');
631
		}
632
633
		$baseClass=ClassInfo::baseDataClass($this->owner->class);
634
		return Versioned::get_including_deleted($baseClass,
635
			"\"ParentID\" = " . (int)$this->owner->ID, "\"$baseClass\".\"ID\" ASC");
636
	}
637
638
	/**
639
	 * Return the number of children that this page ever had, including pages that were deleted.
640
	 *
641
	 * @return int
642
	 * @throws Exception
643
	 */
644
	public function numHistoricalChildren() {
645
		if(!$this->owner->hasExtension('Versioned')) {
646
			throw new Exception('Hierarchy->AllHistoricalChildren() only works with Versioned extension applied');
647
		}
648
649
		return Versioned::get_including_deleted(ClassInfo::baseDataClass($this->owner->class),
650
			"\"ParentID\" = " . (int)$this->owner->ID)->count();
651
	}
652
653
	/**
654
	 * Return the number of direct children. By default, values are cached after the first invocation. Can be
655
	 * augumented by {@link augmentNumChildrenCountQuery()}.
656
	 *
657
	 * @param bool $cache Whether to retrieve values from cache
658
	 * @return int
659
	 */
660
	public function numChildren($cache = true) {
661
		// Build the cache for this class if it doesn't exist.
662
		if(!$cache || !is_numeric($this->_cache_numChildren)) {
663
			// Hey, this is efficient now!
664
			// We call stageChildren(), because Children() has canView() filtering
665
			$this->_cache_numChildren = (int)$this->owner->stageChildren(true)->Count();
666
		}
667
668
		// If theres no value in the cache, it just means that it doesn't have any children.
669
		return $this->_cache_numChildren;
670
	}
671
672
	/**
673
	 * Checks if we're on a controller where we should filter. ie. Are we loading the SiteTree?
674
	 *
675
	 * @return bool
676
	 */
677
	public function showingCMSTree() {
678
		if (!Controller::has_curr()) return false;
679
		$controller = Controller::curr();
680
		return $controller instanceof LeftAndMain
681
			&& in_array($controller->getAction(), array("treeview", "listview", "getsubtree"));
682
	}
683
684
	/**
685
	 * Return children in the stage site.
686
	 *
687
	 * @param bool $showAll Include all of the elements, even those not shown in the menus. Only applicable when
688
	 *                      extension is applied to {@link SiteTree}.
689
	 * @return DataList
690
	 */
691
	public function stageChildren($showAll = false) {
692
		$baseClass = ClassInfo::baseDataClass($this->owner->class);
693
		$hide_from_hierarchy = $this->owner->config()->hide_from_hierarchy;
0 ignored issues
show
Documentation introduced by
The property hide_from_hierarchy does not exist on object<Config_ForClass>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
694
		$hide_from_cms_tree = $this->owner->config()->hide_from_cms_tree;
0 ignored issues
show
Documentation introduced by
The property hide_from_cms_tree does not exist on object<Config_ForClass>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
695
		$staged = $baseClass::get()
696
				->filter('ParentID', (int)$this->owner->ID)
697
				->exclude('ID', (int)$this->owner->ID);
698
		if ($hide_from_hierarchy) {
699
			$staged = $staged->exclude('ClassName', $hide_from_hierarchy);
700
		}
701
		if ($hide_from_cms_tree && $this->showingCMSTree()) {
702
			$staged = $staged->exclude('ClassName', $hide_from_cms_tree);
703
		}
704
		if (!$showAll && $this->owner->db('ShowInMenus')) {
705
			$staged = $staged->filter('ShowInMenus', 1);
706
		}
707
		$this->owner->extend("augmentStageChildren", $staged, $showAll);
708
		return $staged;
709
	}
710
711
	/**
712
	 * Return children in the live site, if it exists.
713
	 *
714
	 * @param bool $showAll              Include all of the elements, even those not shown in the menus. Only
715
	 *                                   applicable when extension is applied to {@link SiteTree}.
716
	 * @param bool $onlyDeletedFromStage Only return items that have been deleted from stage
717
	 * @return DataList
718
	 * @throws Exception
719
	 */
720
	public function liveChildren($showAll = false, $onlyDeletedFromStage = false) {
721
		if(!$this->owner->hasExtension('Versioned')) {
722
			throw new Exception('Hierarchy->liveChildren() only works with Versioned extension applied');
723
		}
724
725
		$baseClass = ClassInfo::baseDataClass($this->owner->class);
726
		$hide_from_hierarchy = $this->owner->config()->hide_from_hierarchy;
0 ignored issues
show
Documentation introduced by
The property hide_from_hierarchy does not exist on object<Config_ForClass>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
727
		$hide_from_cms_tree = $this->owner->config()->hide_from_cms_tree;
0 ignored issues
show
Documentation introduced by
The property hide_from_cms_tree does not exist on object<Config_ForClass>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
728
		$children = $baseClass::get()
729
			->filter('ParentID', (int)$this->owner->ID)
730
			->exclude('ID', (int)$this->owner->ID)
731
			->setDataQueryParam(array(
732
				'Versioned.mode' => $onlyDeletedFromStage ? 'stage_unique' : 'stage',
733
				'Versioned.stage' => 'Live'
734
			));
735
		if ($hide_from_hierarchy) {
736
			$children = $children->exclude('ClassName', $hide_from_hierarchy);
737
		}
738
		if ($hide_from_cms_tree && $this->showingCMSTree()) {
739
			$children = $children->exclude('ClassName', $hide_from_cms_tree);
740
		}
741
		if(!$showAll && $this->owner->db('ShowInMenus')) $children = $children->filter('ShowInMenus', 1);
742
743
		return $children;
744
	}
745
746
	/**
747
	 * Get this object's parent, optionally filtered by an SQL clause. If the clause doesn't match the parent, nothing
748
	 * is returned.
749
	 *
750
	 * @param string $filter
751
	 * @return DataObject
752
	 */
753
	public function getParent($filter = null) {
754
		if($p = $this->owner->__get("ParentID")) {
755
			$tableClasses = ClassInfo::dataClassesFor($this->owner->class);
756
			$baseClass = array_shift($tableClasses);
757
			return DataObject::get_one($this->owner->class, array(
758
				array("\"$baseClass\".\"ID\"" => $p),
759
				$filter
760
			));
761
		}
762
	}
763
764
	/**
765
	 * Return all the parents of this class in a set ordered from the lowest to highest parent.
766
	 *
767
	 * @return ArrayList
768
	 */
769
	public function getAncestors() {
770
		$ancestors = new ArrayList();
771
		$object    = $this->owner;
772
773
		while($object = $object->getParent()) {
774
			$ancestors->push($object);
775
		}
776
777
		return $ancestors;
778
	}
779
780
	/**
781
	 * Returns a human-readable, flattened representation of the path to the object, using its {@link Title} attribute.
782
	 *
783
	 * @param string $separator
784
	 * @return string
785
	 */
786
	public function getBreadcrumbs($separator = ' &raquo; ') {
787
		$crumbs = array();
788
		$ancestors = array_reverse($this->owner->getAncestors()->toArray());
789
		foreach($ancestors as $ancestor) $crumbs[] = $ancestor->Title;
790
		$crumbs[] = $this->owner->Title;
0 ignored issues
show
Documentation introduced by
The property Title does not exist on object<DataObject>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
791
		return implode($separator, $crumbs);
792
	}
793
794
	/**
795
	 * Get the next node in the tree of the type. If there is no instance of the className descended from this node,
796
	 * then search the parents.
797
	 *
798
	 * @todo Write!
799
	 *
800
	 * @param string     $className Class name of the node to find
801
	 * @param DataObject $afterNode Used for recursive calls to this function
802
	 * @return DataObject
803
	 */
804
	public function naturalPrev($className, $afterNode = null ) {
0 ignored issues
show
Unused Code introduced by
The parameter $className is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $afterNode is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
805
		return null;
806
	}
807
808
	/**
809
	 * Get the next node in the tree of the type. If there is no instance of the className descended from this node,
810
	 * then search the parents.
811
	 * @param string     $className Class name of the node to find.
812
	 * @param string|int $root      ID/ClassName of the node to limit the search to
813
	 * @param DataObject $afterNode Used for recursive calls to this function
814
	 * @return DataObject
815
	 */
816
	public function naturalNext($className = null, $root = 0, $afterNode = null ) {
817
		// If this node is not the node we are searching from, then we can possibly return this node as a solution
818
		if($afterNode && $afterNode->ID != $this->owner->ID) {
819
			if(!$className || ($className && $this->owner->class == $className)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $className of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
820
				return $this->owner;
821
			}
822
		}
823
824
		$nextNode = null;
825
		$baseClass = ClassInfo::baseDataClass($this->owner->class);
826
827
		$children = $baseClass::get()
828
			->filter('ParentID', (int)$this->owner->ID)
829
			->sort('"Sort"', 'ASC');
830
		if ($afterNode) {
831
			$children = $children->filter('Sort:GreaterThan', $afterNode->Sort);
832
		}
833
834
		// Try all the siblings of this node after the given node
835
		/*if( $siblings = DataObject::get( ClassInfo::baseDataClass($this->owner->class),
0 ignored issues
show
Unused Code Comprehensibility introduced by
52% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
836
		"\"ParentID\"={$this->owner->ParentID}" . ( $afterNode ) ? "\"Sort\"
837
		> {$afterNode->Sort}" : "" , '\"Sort\" ASC' ) ) $searchNodes->merge( $siblings );*/
838
839
		if($children) {
840
			foreach($children as $node) {
841
				if($nextNode = $node->naturalNext($className, $node->ID, $this->owner)) {
842
					break;
843
				}
844
			}
845
846
			if($nextNode) {
847
				return $nextNode;
848
			}
849
		}
850
851
		// if this is not an instance of the root class or has the root id, search the parent
852
		if(!(is_numeric($root) && $root == $this->owner->ID || $root == $this->owner->class)
853
				&& ($parent = $this->owner->Parent())) {
0 ignored issues
show
Bug introduced by
The method Parent() does not exist on DataObject. Did you maybe mean parentClass()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
854
855
			return $parent->naturalNext( $className, $root, $this->owner );
856
		}
857
858
		return null;
859
	}
860
861
	/**
862
	 * Flush all Hierarchy caches:
863
	 * - Children (instance)
864
	 * - NumChildren (instance)
865
	 * - Marked (global)
866
	 * - Expanded (global)
867
	 * - TreeOpened (global)
868
	 */
869
	public function flushCache() {
870
		$this->_cache_children = null;
871
		$this->_cache_numChildren = null;
872
		self::$marked = array();
873
		self::$expanded = array();
874
		self::$treeOpened = array();
875
	}
876
877
	/**
878
	 * Reset global Hierarchy caches:
879
	 * - Marked
880
	 * - Expanded
881
	 * - TreeOpened
882
	 */
883
	public static function reset() {
884
		self::$marked = array();
885
		self::$expanded = array();
886
		self::$treeOpened = array();
887
	}
888
889
}
890