Completed
Push — 3.4 ( 8b1af9...5b200d )
by Damian
18s
created

Hierarchy::getChildrenAsUL()   C

Complexity

Conditions 20
Paths 100

Size

Total Lines 78
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 20
eloc 45
nc 100
nop 9
dl 0
loc 78
rs 5.111
c 0
b 0
f 0

How to fix   Long Method    Complexity    Many Parameters   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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
	public static function get_extra_config($class, $extension, $args) {
45
		return array(
46
			'has_one' => array('Parent' => $class)
47
		);
48
	}
49
50
	/**
51
	 * Validate the owner object - check for existence of infinite loops.
52
	 *
53
	 * @param ValidationResult $validationResult
54
	 */
55
	public function validate(ValidationResult $validationResult) {
56
		// The object is new, won't be looping.
57
		if (!$this->owner->ID) return;
58
		// The object has no parent, won't be looping.
59
		if (!$this->owner->ParentID) return;
60
		// The parent has not changed, skip the check for performance reasons.
61
		if (!$this->owner->isChanged('ParentID')) return;
62
63
		// Walk the hierarchy upwards until we reach the top, or until we reach the originating node again.
64
		$node = $this->owner;
65
		while($node) {
66
			if ($node->ParentID==$this->owner->ID) {
67
				// Hierarchy is looping.
68
				$validationResult->error(
69
					_t(
70
						'Hierarchy.InfiniteLoopNotAllowed',
71
						'Infinite loop found within the "{type}" hierarchy. Please change the parent to resolve this',
72
						'First argument is the class that makes up the hierarchy.',
73
						array('type' => $this->owner->class)
74
					),
75
					'INFINITE_LOOP'
76
				);
77
				break;
78
			}
79
			$node = $node->ParentID ? $node->Parent() : null;
80
		}
81
82
		// At this point the $validationResult contains the response.
83
	}
84
85
	/**
86
	 * Returns the children of this DataObject as an XHTML UL. This will be called recursively on each child, so if they
87
	 * have children they will be displayed as a UL inside a LI.
88
	 *
89
	 * @param string          $attributes         Attributes to add to the UL
90
	 * @param string|callable $titleEval          PHP code to evaluate to start each child - this should include '<li>'
91
	 * @param string          $extraArg           Extra arguments that will be passed on to children, for if they
92
	 *                                            overload this function
93
	 * @param bool            $limitToMarked      Display only marked children
94
	 * @param string          $childrenMethod     The name of the method used to get children from each object
95
	 * @param bool            $rootCall           Set to true for this first call, and then to false for calls inside
96
	 *                                            the recursion. You should not change this.
97
	 * @param int             $nodeCountThreshold See {@link self::$node_threshold_total}
98
	 * @param callable        $nodeCountCallback  Called with the node count, which gives the callback an opportunity to
99
	 *                                            intercept the query. Useful e.g. to avoid excessive children listings
100
	 *                                            (Arguments: $parent, $numChildren)
101
	 *
102
	 * @return string
103
	 */
104
	public function getChildrenAsUL($attributes = "", $titleEval = '"<li>" . $child->Title', $extraArg = null,
105
			$limitToMarked = false, $childrenMethod = "AllChildrenIncludingDeleted",
106
			$numChildrenMethod = "numChildren", $rootCall = true,
107
			$nodeCountThreshold = null, $nodeCountCallback = null) {
108
109
		if(!is_numeric($nodeCountThreshold)) {
110
			$nodeCountThreshold = Config::inst()->get('Hierarchy', 'node_threshold_total');
111
		}
112
113
		if($limitToMarked && $rootCall) {
114
			$this->markingFinished($numChildrenMethod);
115
		}
116
117
118
		if($nodeCountCallback) {
119
			$nodeCountWarning = $nodeCountCallback($this->owner, $this->owner->$numChildrenMethod());
120
			if($nodeCountWarning) return $nodeCountWarning;
121
		}
122
123
124
		if($this->owner->hasMethod($childrenMethod)) {
125
			$children = $this->owner->$childrenMethod($extraArg);
126
		} else {
127
			user_error(sprintf("Can't find the method '%s' on class '%s' for getting tree children",
128
				$childrenMethod, get_class($this->owner)), E_USER_ERROR);
129
		}
130
131
		if($children) {
132
133
			if($attributes) {
134
				$attributes = " $attributes";
135
			}
136
137
			$output = "<ul$attributes>\n";
138
139
			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...
140
				if(!$limitToMarked || $child->isMarked()) {
141
					$foundAChild = true;
142
					if(is_callable($titleEval)) {
143
						$output .= $titleEval($child, $numChildrenMethod);
144
					} else {
145
						$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...
146
					}
147
					$output .= "\n";
148
149
					$numChildren = $child->$numChildrenMethod();
150
151
					if(
152
						// Always traverse into opened nodes (they might be exposed as parents of search results)
153
						$child->isExpanded()
154
						// Only traverse into children if we haven't reached the maximum node count already.
155
						// Otherwise, the remaining nodes are lazy loaded via ajax.
156
						&& $child->isMarked()
157
					) {
158
						// Additionally check if node count requirements are met
159
						$nodeCountWarning = $nodeCountCallback ? $nodeCountCallback($child, $numChildren) : null;
160
						if($nodeCountWarning) {
161
							$output .= $nodeCountWarning;
162
							$child->markClosed();
163
						} else {
164
							$output .= $child->getChildrenAsUL("", $titleEval, $extraArg, $limitToMarked,
165
								$childrenMethod,	$numChildrenMethod, false, $nodeCountThreshold);
166
						}
167
					} elseif($child->isTreeOpened()) {
168
						// Since we're not loading children, don't mark it as open either
169
						$child->markClosed();
170
					}
171
					$output .= "</li>\n";
172
				}
173
			}
174
175
			$output .= "</ul>\n";
176
		}
177
178
		if(isset($foundAChild) && $foundAChild) {
179
			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...
180
		}
181
	}
182
183
	/**
184
	 * Mark a segment of the tree, by calling mark().
185
	 *
186
	 * The method performs a breadth-first traversal until the number of nodes is more than minCount. This is used to
187
	 * get a limited number of tree nodes to show in the CMS initially.
188
	 *
189
	 * This method returns the number of nodes marked.  After this method is called other methods can check
190
	 * {@link isExpanded()} and {@link isMarked()} on individual nodes.
191
	 *
192
	 * @param int $nodeCountThreshold See {@link getChildrenAsUL()}
193
	 * @return int The actual number of nodes marked.
194
	 */
195
	public function markPartialTree($nodeCountThreshold = 30, $context = null,
196
			$childrenMethod = "AllChildrenIncludingDeleted", $numChildrenMethod = "numChildren") {
197
198
		if(!is_numeric($nodeCountThreshold)) $nodeCountThreshold = 30;
199
200
		$this->markedNodes = array($this->owner->ID => $this->owner);
201
		$this->owner->markUnexpanded();
202
203
		// foreach can't handle an ever-growing $nodes list
204
		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...
205
			$children = $this->markChildren($node, $context, $childrenMethod, $numChildrenMethod);
206
			if($nodeCountThreshold && sizeof($this->markedNodes) > $nodeCountThreshold) {
207
				// Undo marking children as opened since they're lazy loaded
208
				if($children) foreach($children as $child) $child->markClosed();
209
				break;
210
			}
211
		}
212
		return sizeof($this->markedNodes);
213
	}
214
215
	/**
216
	 * Filter the marking to only those object with $node->$parameterName == $parameterValue
217
	 *
218
	 * @param string $parameterName  The parameter on each node to check when marking.
219
	 * @param mixed  $parameterValue The value the parameter must be to be marked.
220
	 */
221
	public function setMarkingFilter($parameterName, $parameterValue) {
222
		$this->markingFilter = array(
223
			"parameter" => $parameterName,
224
			"value" => $parameterValue
225
		);
226
	}
227
228
	/**
229
	 * Filter the marking to only those where the function returns true. The node in question will be passed to the
230
	 * function.
231
	 *
232
	 * @param string $funcName The name of the function to call
233
	 */
234
	public function setMarkingFilterFunction($funcName) {
235
		$this->markingFilter = array(
236
			"func" => $funcName,
237
		);
238
	}
239
240
	/**
241
	 * Returns true if the marking filter matches on the given node.
242
	 *
243
	 * @param DataObject $node Node to check
244
	 * @return bool
245
	 */
246
	public function markingFilterMatches($node) {
247
		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...
248
			return true;
249
		}
250
251
		if(isset($this->markingFilter['parameter']) && $parameterName = $this->markingFilter['parameter']) {
252
			if(is_array($this->markingFilter['value'])){
253
				$ret = false;
254
				foreach($this->markingFilter['value'] as $value) {
255
					$ret = $ret||$node->$parameterName==$value;
256
					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...
257
						break;
258
					}
259
				}
260
				return $ret;
261
			} else {
262
				return ($node->$parameterName == $this->markingFilter['value']);
263
			}
264
		} else if ($func = $this->markingFilter['func']) {
265
			return call_user_func($func, $node);
266
		}
267
	}
268
269
	/**
270
	 * Mark all children of the given node that match the marking filter.
271
	 *
272
	 * @param DataObject $node              Parent node
273
	 * @param mixed      $context
274
	 * @param string     $childrenMethod    The name of the instance method to call to get the object's list of children
275
	 * @param string     $numChildrenMethod The name of the instance method to call to count the object's children
276
	 * @return DataList
277
	 */
278
	public function markChildren($node, $context = null, $childrenMethod = "AllChildrenIncludingDeleted",
279
			$numChildrenMethod = "numChildren") {
280
		if($node->hasMethod($childrenMethod)) {
281
			$children = $node->$childrenMethod($context);
282
		} else {
283
			user_error(sprintf("Can't find the method '%s' on class '%s' for getting tree children",
284
				$childrenMethod, get_class($node)), E_USER_ERROR);
285
		}
286
287
		$node->markExpanded();
288
		if($children) {
289
			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...
290
				$markingMatches = $this->markingFilterMatches($child);
291
				if($markingMatches) {
292
					// Mark a child node as unexpanded if it has children and has not already been expanded
293
					if($child->$numChildrenMethod() && !$child->isExpanded()) {
294
						$child->markUnexpanded();
295
					} else {
296
						$child->markExpanded();
297
					}
298
					$this->markedNodes[$child->ID] = $child;
299
				}
300
			}
301
		}
302
303
		return $children;
304
	}
305
306
	/**
307
	 * Ensure marked nodes that have children are also marked expanded. Call this after marking but before iterating
308
	 * over the tree.
309
	 *
310
	 * @param string $numChildrenMethod The name of the instance method to call to count the object's children
311
	 */
312
	protected function markingFinished($numChildrenMethod = "numChildren") {
313
		// Mark childless nodes as expanded.
314
		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...
315
			foreach($this->markedNodes as $id => $node) {
316
				if(!$node->isExpanded() && !$node->$numChildrenMethod()) {
317
					$node->markExpanded();
318
				}
319
			}
320
		}
321
	}
322
323
	/**
324
	 * Return CSS classes of 'unexpanded', 'closed', both, or neither, as well as a 'jstree-*' state depending on the
325
	 * marking of this DataObject.
326
	 *
327
	 * @param string $numChildrenMethod The name of the instance method to call to count the object's children
328
	 * @return string
329
	 */
330
	public function markingClasses($numChildrenMethod="numChildren") {
331
		$classes = '';
332
		if(!$this->isExpanded()) {
333
			$classes .= " unexpanded";
334
		}
335
336
		// Set jstree open state, or mark it as a leaf (closed) if there are no children
337
		if(!$this->owner->$numChildrenMethod()) {
338
			$classes .= " jstree-leaf closed";
339
		} elseif($this->isTreeOpened()) {
340
			$classes .= " jstree-open";
341
		} else {
342
			$classes .= " jstree-closed closed";
343
		}
344
		return $classes;
345
	}
346
347
	/**
348
	 * Mark the children of the DataObject with the given ID.
349
	 *
350
	 * @param int  $id   ID of parent node
351
	 * @param bool $open If this is true, mark the parent node as opened
352
	 * @return bool
353
	 */
354
	public function markById($id, $open = false) {
355
		if(isset($this->markedNodes[$id])) {
356
			$this->markChildren($this->markedNodes[$id]);
357
			if($open) {
358
				$this->markedNodes[$id]->markOpened();
359
			}
360
			return true;
361
		} else {
362
			return false;
363
		}
364
	}
365
366
	/**
367
	 * Expose the given object in the tree, by marking this page and all it ancestors.
368
	 *
369
	 * @param DataObject $childObj
370
	 */
371
	public function markToExpose($childObj) {
372
		if(is_object($childObj)){
373
			$stack = array_reverse($childObj->parentStack());
374
			foreach($stack as $stackItem) {
375
				$this->markById($stackItem->ID, true);
376
			}
377
		}
378
	}
379
380
	/**
381
	 * Return the IDs of all the marked nodes.
382
	 *
383
	 * @return array
384
	 */
385
	public function markedNodeIDs() {
386
		return array_keys($this->markedNodes);
387
	}
388
389
	/**
390
	 * Return an array of this page and its ancestors, ordered item -> root.
391
	 *
392
	 * @return SiteTree[]
393
	 */
394
	public function parentStack() {
395
		$p = $this->owner;
396
397
		while($p) {
398
			$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...
399
			$p = $p->ParentID ? $p->Parent() : null;
400
		}
401
402
		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...
403
	}
404
405
	/**
406
	 * Cache of DataObjects' marked statuses: [ClassName][ID] = bool
407
	 * @var array
408
	 */
409
	protected static $marked = array();
410
411
	/**
412
	 * Cache of DataObjects' expanded statuses: [ClassName][ID] = bool
413
	 * @var array
414
	 */
415
	protected static $expanded = array();
416
417
	/**
418
	 * Cache of DataObjects' opened statuses: [ClassName][ID] = bool
419
	 * @var array
420
	 */
421
	protected static $treeOpened = array();
422
423
	/**
424
	 * Mark this DataObject as expanded.
425
	 */
426
	public function markExpanded() {
427
		self::$marked[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID] = true;
428
		self::$expanded[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID] = true;
429
	}
430
431
	/**
432
	 * Mark this DataObject as unexpanded.
433
	 */
434
	public function markUnexpanded() {
435
		self::$marked[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID] = true;
436
		self::$expanded[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID] = false;
437
	}
438
439
	/**
440
	 * Mark this DataObject's tree as opened.
441
	 */
442
	public function markOpened() {
443
		self::$marked[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID] = true;
444
		self::$treeOpened[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID] = true;
445
	}
446
447
	/**
448
	 * Mark this DataObject's tree as closed.
449
	 */
450
	public function markClosed() {
451
		if(isset(self::$treeOpened[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID])) {
452
			unset(self::$treeOpened[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID]);
453
		}
454
	}
455
456
	/**
457
	 * Check if this DataObject is marked.
458
	 *
459
	 * @return bool
460
	 */
461
	public function isMarked() {
462
		$baseClass = ClassInfo::baseDataClass($this->owner->class);
463
		$id = $this->owner->ID;
464
		return isset(self::$marked[$baseClass][$id]) ? self::$marked[$baseClass][$id] : false;
465
	}
466
467
	/**
468
	 * Check if this DataObject is expanded.
469
	 *
470
	 * @return bool
471
	 */
472
	public function isExpanded() {
473
		$baseClass = ClassInfo::baseDataClass($this->owner->class);
474
		$id = $this->owner->ID;
475
		return isset(self::$expanded[$baseClass][$id]) ? self::$expanded[$baseClass][$id] : false;
476
	}
477
478
	/**
479
	 * Check if this DataObject's tree is opened.
480
	 *
481
	 * @return bool
482
	 */
483
	public function isTreeOpened() {
484
		$baseClass = ClassInfo::baseDataClass($this->owner->class);
485
		$id = $this->owner->ID;
486
		return isset(self::$treeOpened[$baseClass][$id]) ? self::$treeOpened[$baseClass][$id] : false;
487
	}
488
489
	/**
490
	 * Get a list of this DataObject's and all it's descendants IDs.
491
	 *
492
	 * @return int[]
493
	 */
494
	public function getDescendantIDList() {
495
		$idList = array();
496
		$this->loadDescendantIDListInto($idList);
497
		return $idList;
498
	}
499
500
	/**
501
	 * Get a list of this DataObject's and all it's descendants ID, and put them in $idList.
502
	 *
503
	 * @param array $idList Array to put results in.
504
	 */
505
	public function loadDescendantIDListInto(&$idList) {
506
		if($children = $this->AllChildren()) {
507
			foreach($children as $child) {
508
				if(in_array($child->ID, $idList)) {
509
					continue;
510
				}
511
				$idList[] = $child->ID;
512
				$ext = $child->getExtensionInstance('Hierarchy');
513
				$ext->setOwner($child);
514
				$ext->loadDescendantIDListInto($idList);
515
				$ext->clearOwner();
516
			}
517
		}
518
	}
519
520
	/**
521
	 * Get the children for this DataObject.
522
	 *
523
	 * @return DataList
524
	 */
525
	public function Children() {
526
		if(!(isset($this->_cache_children) && $this->_cache_children)) {
527
			$result = $this->owner->stageChildren(false);
528
			$children = array();
529
			foreach ($result as $record) {
530
				if ($record->canView()) {
531
					$children[] = $record;
532
				}
533
			}
534
			$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...
535
		}
536
		return $this->_cache_children;
537
	}
538
539
	/**
540
	 * Return all children, including those 'not in menus'.
541
	 *
542
	 * @return DataList
543
	 */
544
	public function AllChildren() {
545
		return $this->owner->stageChildren(true);
546
	}
547
548
	/**
549
	 * Return all children, including those that have been deleted but are still in live.
550
	 * - Deleted children will be marked as "DeletedFromStage"
551
	 * - Added children will be marked as "AddedToStage"
552
	 * - Modified children will be marked as "ModifiedOnStage"
553
	 * - Everything else has "SameOnStage" set, as an indicator that this information has been looked up.
554
	 *
555
	 * @param mixed $context
556
	 * @return ArrayList
557
	 */
558
	public function AllChildrenIncludingDeleted($context = null) {
559
		return $this->doAllChildrenIncludingDeleted($context);
560
	}
561
562
	/**
563
	 * @see AllChildrenIncludingDeleted
564
	 *
565
	 * @param mixed $context
566
	 * @return ArrayList
567
	 */
568
	public function doAllChildrenIncludingDeleted($context = null) {
569
		if(!$this->owner) user_error('Hierarchy::doAllChildrenIncludingDeleted() called without $this->owner');
570
571
		$baseClass = ClassInfo::baseDataClass($this->owner->class);
572
		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...
573
			$stageChildren = $this->owner->stageChildren(true);
574
575
			// Add live site content that doesn't exist on the stage site, if required.
576
			if($this->owner->hasExtension('Versioned')) {
577
				// Next, go through the live children.  Only some of these will be listed
578
				$liveChildren = $this->owner->liveChildren(true, true);
579
				if($liveChildren) {
580
					$merged = new ArrayList();
581
					$merged->merge($stageChildren);
582
					$merged->merge($liveChildren);
583
					$stageChildren = $merged;
584
				}
585
			}
586
587
			$this->owner->extend("augmentAllChildrenIncludingDeleted", $stageChildren, $context);
588
589
		} else {
590
			user_error("Hierarchy::AllChildren() Couldn't determine base class for '{$this->owner->class}'",
591
				E_USER_ERROR);
592
		}
593
594
		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...
595
	}
596
597
	/**
598
	 * Return all the children that this page had, including pages that were deleted from both stage & live.
599
	 *
600
	 * @return DataList
601
	 * @throws Exception
602
	 */
603
	public function AllHistoricalChildren() {
604
		if(!$this->owner->hasExtension('Versioned')) {
605
			throw new Exception('Hierarchy->AllHistoricalChildren() only works with Versioned extension applied');
606
		}
607
608
		$baseClass=ClassInfo::baseDataClass($this->owner->class);
609
		return Versioned::get_including_deleted($baseClass,
610
			"\"ParentID\" = " . (int)$this->owner->ID, "\"$baseClass\".\"ID\" ASC");
611
	}
612
613
	/**
614
	 * Return the number of children that this page ever had, including pages that were deleted.
615
	 *
616
	 * @return int
617
	 * @throws Exception
618
	 */
619
	public function numHistoricalChildren() {
620
		if(!$this->owner->hasExtension('Versioned')) {
621
			throw new Exception('Hierarchy->AllHistoricalChildren() only works with Versioned extension applied');
622
		}
623
624
		return Versioned::get_including_deleted(ClassInfo::baseDataClass($this->owner->class),
625
			"\"ParentID\" = " . (int)$this->owner->ID)->count();
626
	}
627
628
	/**
629
	 * Return the number of direct children. By default, values are cached after the first invocation. Can be
630
	 * augumented by {@link augmentNumChildrenCountQuery()}.
631
	 *
632
	 * @param bool $cache Whether to retrieve values from cache
633
	 * @return int
634
	 */
635
	public function numChildren($cache = true) {
636
		// Build the cache for this class if it doesn't exist.
637
		if(!$cache || !is_numeric($this->_cache_numChildren)) {
638
			// Hey, this is efficient now!
639
			// We call stageChildren(), because Children() has canView() filtering
640
			$this->_cache_numChildren = (int)$this->owner->stageChildren(true)->Count();
641
		}
642
643
		// If theres no value in the cache, it just means that it doesn't have any children.
644
		return $this->_cache_numChildren;
645
	}
646
647
	/**
648
	 * Return children in the stage site.
649
	 *
650
	 * @param bool $showAll Include all of the elements, even those not shown in the menus. Only applicable when
651
	 *                      extension is applied to {@link SiteTree}.
652
	 * @return DataList
653
	 */
654
	public function stageChildren($showAll = false) {
655
		$baseClass = ClassInfo::baseDataClass($this->owner->class);
656
		$staged = $baseClass::get()
657
			->filter('ParentID', (int)$this->owner->ID)
658
			->exclude('ID', (int)$this->owner->ID);
659
		if (!$showAll && $this->owner->db('ShowInMenus')) {
660
			$staged = $staged->filter('ShowInMenus', 1);
661
		}
662
		$this->owner->extend("augmentStageChildren", $staged, $showAll);
663
		return $staged;
664
	}
665
666
	/**
667
	 * Return children in the live site, if it exists.
668
	 *
669
	 * @param bool $showAll              Include all of the elements, even those not shown in the menus. Only
670
	 *                                   applicable when extension is applied to {@link SiteTree}.
671
	 * @param bool $onlyDeletedFromStage Only return items that have been deleted from stage
672
	 * @return DataList
673
	 * @throws Exception
674
	 */
675
	public function liveChildren($showAll = false, $onlyDeletedFromStage = false) {
676
		if(!$this->owner->hasExtension('Versioned')) {
677
			throw new Exception('Hierarchy->liveChildren() only works with Versioned extension applied');
678
		}
679
680
		$baseClass = ClassInfo::baseDataClass($this->owner->class);
681
		$children = $baseClass::get()
682
			->filter('ParentID', (int)$this->owner->ID)
683
			->exclude('ID', (int)$this->owner->ID)
684
			->setDataQueryParam(array(
685
				'Versioned.mode' => $onlyDeletedFromStage ? 'stage_unique' : 'stage',
686
				'Versioned.stage' => 'Live'
687
			));
688
689
		if(!$showAll) $children = $children->filter('ShowInMenus', 1);
690
691
		return $children;
692
	}
693
694
	/**
695
	 * Get this object's parent, optionally filtered by an SQL clause. If the clause doesn't match the parent, nothing
696
	 * is returned.
697
	 *
698
	 * @param string $filter
699
	 * @return DataObject
700
	 */
701
	public function getParent($filter = null) {
702
		if($p = $this->owner->__get("ParentID")) {
703
			$tableClasses = ClassInfo::dataClassesFor($this->owner->class);
704
			$baseClass = array_shift($tableClasses);
705
			return DataObject::get_one($this->owner->class, array(
706
				array("\"$baseClass\".\"ID\"" => $p),
707
				$filter
708
			));
709
		}
710
	}
711
712
	/**
713
	 * Return all the parents of this class in a set ordered from the lowest to highest parent.
714
	 *
715
	 * @return ArrayList
716
	 */
717
	public function getAncestors() {
718
		$ancestors = new ArrayList();
719
		$object    = $this->owner;
720
721
		while($object = $object->getParent()) {
722
			$ancestors->push($object);
723
		}
724
725
		return $ancestors;
726
	}
727
728
	/**
729
	 * Returns a human-readable, flattened representation of the path to the object, using its {@link Title} attribute.
730
	 *
731
	 * @param string $separator
732
	 * @return string
733
	 */
734
	public function getBreadcrumbs($separator = ' &raquo; ') {
735
		$crumbs = array();
736
		$ancestors = array_reverse($this->owner->getAncestors()->toArray());
737
		foreach($ancestors as $ancestor) $crumbs[] = $ancestor->Title;
738
		$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...
739
		return implode($separator, $crumbs);
740
	}
741
742
	/**
743
	 * Get the next node in the tree of the type. If there is no instance of the className descended from this node,
744
	 * then search the parents.
745
	 *
746
	 * @todo Write!
747
	 *
748
	 * @param string     $className Class name of the node to find
749
	 * @param DataObject $afterNode Used for recursive calls to this function
750
	 * @return DataObject
751
	 */
752
	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...
753
		return null;
754
	}
755
756
	/**
757
	 * Get the next node in the tree of the type. If there is no instance of the className descended from this node,
758
	 * then search the parents.
759
	 * @param string     $className Class name of the node to find.
760
	 * @param string|int $root      ID/ClassName of the node to limit the search to
761
	 * @param DataObject $afterNode Used for recursive calls to this function
762
	 * @return DataObject
763
	 */
764
	public function naturalNext($className = null, $root = 0, $afterNode = null ) {
765
		// If this node is not the node we are searching from, then we can possibly return this node as a solution
766
		if($afterNode && $afterNode->ID != $this->owner->ID) {
767
			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...
768
				return $this->owner;
769
			}
770
		}
771
772
		$nextNode = null;
773
		$baseClass = ClassInfo::baseDataClass($this->owner->class);
774
775
		$children = $baseClass::get()
776
			->filter('ParentID', (int)$this->owner->ID)
777
			->sort('"Sort"', 'ASC');
778
		if ($afterNode) {
779
			$children = $children->filter('Sort:GreaterThan', $afterNode->Sort);
780
		}
781
782
		// Try all the siblings of this node after the given node
783
		/*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...
784
		"\"ParentID\"={$this->owner->ParentID}" . ( $afterNode ) ? "\"Sort\"
785
		> {$afterNode->Sort}" : "" , '\"Sort\" ASC' ) ) $searchNodes->merge( $siblings );*/
786
787
		if($children) {
788
			foreach($children as $node) {
789
				if($nextNode = $node->naturalNext($className, $node->ID, $this->owner)) {
790
					break;
791
				}
792
			}
793
794
			if($nextNode) {
795
				return $nextNode;
796
			}
797
		}
798
799
		// if this is not an instance of the root class or has the root id, search the parent
800
		if(!(is_numeric($root) && $root == $this->owner->ID || $root == $this->owner->class)
801
				&& ($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...
802
803
			return $parent->naturalNext( $className, $root, $this->owner );
804
		}
805
806
		return null;
807
	}
808
809
	/**
810
	 * Flush all Hierarchy caches:
811
	 * - Children (instance)
812
	 * - NumChildren (instance)
813
	 * - Marked (global)
814
	 * - Expanded (global)
815
	 * - TreeOpened (global)
816
	 */
817
	public function flushCache() {
818
		$this->_cache_children = null;
819
		$this->_cache_numChildren = null;
820
		self::$marked = array();
821
		self::$expanded = array();
822
		self::$treeOpened = array();
823
	}
824
825
	/**
826
	 * Reset global Hierarchy caches:
827
	 * - Marked
828
	 * - Expanded
829
	 * - TreeOpened
830
	 */
831
	public static function reset() {
832
		self::$marked = array();
833
		self::$expanded = array();
834
		self::$treeOpened = array();
835
	}
836
837
}
838