Completed
Push — sitetree-docblock-improvements ( a5bc4a...979142 )
by Sam
14:30 queued 08:11
created

Hierarchy::flushCache()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 6

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 7
rs 9.4285
cc 1
eloc 6
nc 1
nop 0
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)
0 ignored issues
show
Documentation introduced by
array('type' => $this->owner->class) is of type array<string,string,{"type":"string"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
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;");
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
					if($child->$numChildrenMethod()) {
293
						$child->markUnexpanded();
294
					} else {
295
						$child->markExpanded();
296
					}
297
					$this->markedNodes[$child->ID] = $child;
298
				}
299
			}
300
		}
301
302
		return $children;
303
	}
304
305
	/**
306
	 * Ensure marked nodes that have children are also marked expanded. Call this after marking but before iterating
307
	 * over the tree.
308
	 *
309
	 * @param string $numChildrenMethod The name of the instance method to call to count the object's children
310
	 */
311
	protected function markingFinished($numChildrenMethod = "numChildren") {
312
		// Mark childless nodes as expanded.
313
		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...
314
			foreach($this->markedNodes as $id => $node) {
315
				if(!$node->isExpanded() && !$node->$numChildrenMethod()) {
316
					$node->markExpanded();
317
				}
318
			}
319
		}
320
	}
321
322
	/**
323
	 * Return CSS classes of 'unexpanded', 'closed', both, or neither, as well as a 'jstree-*' state depending on the
324
	 * marking of this DataObject.
325
	 *
326
	 * @param string $numChildrenMethod The name of the instance method to call to count the object's children
327
	 * @return string
328
	 */
329
	public function markingClasses($numChildrenMethod="numChildren") {
330
		$classes = '';
331
		if(!$this->isExpanded()) {
332
			$classes .= " unexpanded";
333
		}
334
335
		// Set jstree open state, or mark it as a leaf (closed) if there are no children
336
		if(!$this->owner->$numChildrenMethod()) {
337
			$classes .= " jstree-leaf closed";
338
		} elseif($this->isTreeOpened()) {
339
			$classes .= " jstree-open";
340
		} else {
341
			$classes .= " jstree-closed closed";
342
		}
343
		return $classes;
344
	}
345
346
	/**
347
	 * Mark the children of the DataObject with the given ID.
348
	 *
349
	 * @param int  $id   ID of parent node
350
	 * @param bool $open If this is true, mark the parent node as opened
351
	 * @return bool
352
	 */
353
	public function markById($id, $open = false) {
354
		if(isset($this->markedNodes[$id])) {
355
			$this->markChildren($this->markedNodes[$id]);
356
			if($open) {
357
				$this->markedNodes[$id]->markOpened();
358
			}
359
			return true;
360
		} else {
361
			return false;
362
		}
363
	}
364
365
	/**
366
	 * Expose the given object in the tree, by marking this page and all it ancestors.
367
	 *
368
	 * @param DataObject $childObj
369
	 */
370
	public function markToExpose($childObj) {
371
		if(is_object($childObj)){
372
			$stack = array_reverse($childObj->parentStack());
373
			foreach($stack as $stackItem) {
374
				$this->markById($stackItem->ID, true);
375
			}
376
		}
377
	}
378
379
	/**
380
	 * Return the IDs of all the marked nodes.
381
	 *
382
	 * @return array
383
	 */
384
	public function markedNodeIDs() {
385
		return array_keys($this->markedNodes);
386
	}
387
388
	/**
389
	 * Return an array of this page and its ancestors, ordered item -> root.
390
	 *
391
	 * @return SiteTree[]
392
	 */
393
	public function parentStack() {
394
		$p = $this->owner;
395
396
		while($p) {
397
			$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...
398
			$p = $p->ParentID ? $p->Parent() : null;
399
		}
400
401
		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...
402
	}
403
404
	/**
405
	 * Cache of DataObjects' marked statuses: [ClassName][ID] = bool
406
	 * @var array
407
	 */
408
	protected static $marked = array();
409
410
	/**
411
	 * Cache of DataObjects' expanded statuses: [ClassName][ID] = bool
412
	 * @var array
413
	 */
414
	protected static $expanded = array();
415
416
	/**
417
	 * Cache of DataObjects' opened statuses: [ClassName][ID] = bool
418
	 * @var array
419
	 */
420
	protected static $treeOpened = array();
421
422
	/**
423
	 * Mark this DataObject as expanded.
424
	 */
425
	public function markExpanded() {
426
		self::$marked[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID] = true;
427
		self::$expanded[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID] = true;
428
	}
429
430
	/**
431
	 * Mark this DataObject as unexpanded.
432
	 */
433
	public function markUnexpanded() {
434
		self::$marked[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID] = true;
435
		self::$expanded[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID] = false;
436
	}
437
438
	/**
439
	 * Mark this DataObject's tree as opened.
440
	 */
441
	public function markOpened() {
442
		self::$marked[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID] = true;
443
		self::$treeOpened[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID] = true;
444
	}
445
446
	/**
447
	 * Mark this DataObject's tree as closed.
448
	 */
449
	public function markClosed() {
450
		if(isset(self::$treeOpened[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID])) {
451
			unset(self::$treeOpened[ClassInfo::baseDataClass($this->owner->class)][$this->owner->ID]);
452
		}
453
	}
454
455
	/**
456
	 * Check if this DataObject is marked.
457
	 *
458
	 * @return bool
459
	 */
460
	public function isMarked() {
461
		$baseClass = ClassInfo::baseDataClass($this->owner->class);
462
		$id = $this->owner->ID;
463
		return isset(self::$marked[$baseClass][$id]) ? self::$marked[$baseClass][$id] : false;
464
	}
465
466
	/**
467
	 * Check if this DataObject is expanded.
468
	 *
469
	 * @return bool
470
	 */
471
	public function isExpanded() {
472
		$baseClass = ClassInfo::baseDataClass($this->owner->class);
473
		$id = $this->owner->ID;
474
		return isset(self::$expanded[$baseClass][$id]) ? self::$expanded[$baseClass][$id] : false;
475
	}
476
477
	/**
478
	 * Check if this DataObject's tree is opened.
479
	 *
480
	 * @return bool
481
	 */
482
	public function isTreeOpened() {
483
		$baseClass = ClassInfo::baseDataClass($this->owner->class);
484
		$id = $this->owner->ID;
485
		return isset(self::$treeOpened[$baseClass][$id]) ? self::$treeOpened[$baseClass][$id] : false;
486
	}
487
488
	/**
489
	 * Get a list of this DataObject's and all it's descendants IDs.
490
	 *
491
	 * @return int[]
492
	 */
493
	public function getDescendantIDList() {
494
		$idList = array();
495
		$this->loadDescendantIDListInto($idList);
496
		return $idList;
497
	}
498
499
	/**
500
	 * Get a list of this DataObject's and all it's descendants ID, and put them in $idList.
501
	 *
502
	 * @param array $idList Array to put results in.
503
	 */
504
	public function loadDescendantIDListInto(&$idList) {
505
		if($children = $this->AllChildren()) {
506
			foreach($children as $child) {
507
				if(in_array($child->ID, $idList)) {
508
					continue;
509
				}
510
				$idList[] = $child->ID;
511
				$ext = $child->getExtensionInstance('Hierarchy');
512
				$ext->setOwner($child);
513
				$ext->loadDescendantIDListInto($idList);
514
				$ext->clearOwner();
515
			}
516
		}
517
	}
518
519
	/**
520
	 * Get the children for this DataObject.
521
	 *
522
	 * @return DataList
523
	 */
524
	public function Children() {
525
		if(!(isset($this->_cache_children) && $this->_cache_children)) {
526
			$result = $this->owner->stageChildren(false);
527
			$children = array();
528
			foreach ($result as $record) {
529
				if ($record->canView()) {
530
					$children[] = $record;
531
				}
532
			}
533
			$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...
534
		}
535
		return $this->_cache_children;
536
	}
537
538
	/**
539
	 * Return all children, including those 'not in menus'.
540
	 *
541
	 * @return DataList
542
	 */
543
	public function AllChildren() {
544
		return $this->owner->stageChildren(true);
545
	}
546
547
	/**
548
	 * Return all children, including those that have been deleted but are still in live.
549
	 * - Deleted children will be marked as "DeletedFromStage"
550
	 * - Added children will be marked as "AddedToStage"
551
	 * - Modified children will be marked as "ModifiedOnStage"
552
	 * - Everything else has "SameOnStage" set, as an indicator that this information has been looked up.
553
	 *
554
	 * @param mixed $context
555
	 * @return ArrayList
556
	 */
557
	public function AllChildrenIncludingDeleted($context = null) {
558
		return $this->doAllChildrenIncludingDeleted($context);
559
	}
560
561
	/**
562
	 * @see AllChildrenIncludingDeleted
563
	 *
564
	 * @param mixed $context
565
	 * @return ArrayList
566
	 */
567
	public function doAllChildrenIncludingDeleted($context = null) {
568
		if(!$this->owner) user_error('Hierarchy::doAllChildrenIncludingDeleted() called without $this->owner');
569
570
		$baseClass = ClassInfo::baseDataClass($this->owner->class);
571
		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...
572
			$stageChildren = $this->owner->stageChildren(true);
573
574
			// Add live site content that doesn't exist on the stage site, if required.
575
			if($this->owner->hasExtension('Versioned')) {
576
				// Next, go through the live children.  Only some of these will be listed
577
				$liveChildren = $this->owner->liveChildren(true, true);
578
				if($liveChildren) {
579
					$merged = new ArrayList();
580
					$merged->merge($stageChildren);
581
					$merged->merge($liveChildren);
582
					$stageChildren = $merged;
583
				}
584
			}
585
586
			$this->owner->extend("augmentAllChildrenIncludingDeleted", $stageChildren, $context);
587
588
		} else {
589
			user_error("Hierarchy::AllChildren() Couldn't determine base class for '{$this->owner->class}'",
590
				E_USER_ERROR);
591
		}
592
593
		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...
594
	}
595
596
	/**
597
	 * Return all the children that this page had, including pages that were deleted from both stage & live.
598
	 *
599
	 * @return DataList
600
	 * @throws Exception
601
	 */
602
	public function AllHistoricalChildren() {
603
		if(!$this->owner->hasExtension('Versioned')) {
604
			throw new Exception('Hierarchy->AllHistoricalChildren() only works with Versioned extension applied');
605
		}
606
607
		$baseClass=ClassInfo::baseDataClass($this->owner->class);
608
		return Versioned::get_including_deleted($baseClass,
609
			"\"ParentID\" = " . (int)$this->owner->ID, "\"$baseClass\".\"ID\" ASC");
610
	}
611
612
	/**
613
	 * Return the number of children that this page ever had, including pages that were deleted.
614
	 *
615
	 * @return int
616
	 * @throws Exception
617
	 */
618
	public function numHistoricalChildren() {
619
		if(!$this->owner->hasExtension('Versioned')) {
620
			throw new Exception('Hierarchy->AllHistoricalChildren() only works with Versioned extension applied');
621
		}
622
623
		return Versioned::get_including_deleted(ClassInfo::baseDataClass($this->owner->class),
624
			"\"ParentID\" = " . (int)$this->owner->ID)->count();
625
	}
626
627
	/**
628
	 * Return the number of direct children. By default, values are cached after the first invocation. Can be
629
	 * augumented by {@link augmentNumChildrenCountQuery()}.
630
	 *
631
	 * @param bool $cache Whether to retrieve values from cache
632
	 * @return int
633
	 */
634
	public function numChildren($cache = true) {
635
		// Build the cache for this class if it doesn't exist.
636
		if(!$cache || !is_numeric($this->_cache_numChildren)) {
637
			// Hey, this is efficient now!
638
			// We call stageChildren(), because Children() has canView() filtering
639
			$this->_cache_numChildren = (int)$this->owner->stageChildren(true)->Count();
640
		}
641
642
		// If theres no value in the cache, it just means that it doesn't have any children.
643
		return $this->_cache_numChildren;
644
	}
645
646
	/**
647
	 * Return children in the stage site.
648
	 *
649
	 * @param bool $showAll Include all of the elements, even those not shown in the menus. Only applicable when
650
	 *                      extension is applied to {@link SiteTree}.
651
	 * @return DataList
652
	 */
653
	public function stageChildren($showAll = false) {
654
		$baseClass = ClassInfo::baseDataClass($this->owner->class);
655
		$staged = $baseClass::get()
656
			->filter('ParentID', (int)$this->owner->ID)
657
			->exclude('ID', (int)$this->owner->ID);
658
		if (!$showAll && $this->owner->db('ShowInMenus')) {
659
			$staged = $staged->filter('ShowInMenus', 1);
660
		}
661
		$this->owner->extend("augmentStageChildren", $staged, $showAll);
662
		return $staged;
663
	}
664
665
	/**
666
	 * Return children in the live site, if it exists.
667
	 *
668
	 * @param bool $showAll              Include all of the elements, even those not shown in the menus. Only
669
	 *                                   applicable when extension is applied to {@link SiteTree}.
670
	 * @param bool $onlyDeletedFromStage Only return items that have been deleted from stage
671
	 * @return DataList
672
	 * @throws Exception
673
	 */
674
	public function liveChildren($showAll = false, $onlyDeletedFromStage = false) {
675
		if(!$this->owner->hasExtension('Versioned')) {
676
			throw new Exception('Hierarchy->liveChildren() only works with Versioned extension applied');
677
		}
678
679
		$baseClass = ClassInfo::baseDataClass($this->owner->class);
680
		$children = $baseClass::get()
681
			->filter('ParentID', (int)$this->owner->ID)
682
			->exclude('ID', (int)$this->owner->ID)
683
			->setDataQueryParam(array(
684
				'Versioned.mode' => $onlyDeletedFromStage ? 'stage_unique' : 'stage',
685
				'Versioned.stage' => 'Live'
686
			));
687
688
		if(!$showAll) $children = $children->filter('ShowInMenus', 1);
689
690
		return $children;
691
	}
692
693
	/**
694
	 * Get this object's parent, optionally filtered by an SQL clause. If the clause doesn't match the parent, nothing
695
	 * is returned.
696
	 *
697
	 * @param string $filter
698
	 * @return DataObject
699
	 */
700
	public function getParent($filter = null) {
701
		if($p = $this->owner->__get("ParentID")) {
702
			$tableClasses = ClassInfo::dataClassesFor($this->owner->class);
703
			$baseClass = array_shift($tableClasses);
704
			return DataObject::get_one($this->owner->class, array(
705
				array("\"$baseClass\".\"ID\"" => $p),
706
				$filter
707
			));
708
		}
709
	}
710
711
	/**
712
	 * Return all the parents of this class in a set ordered from the lowest to highest parent.
713
	 *
714
	 * @return ArrayList
715
	 */
716
	public function getAncestors() {
717
		$ancestors = new ArrayList();
718
		$object    = $this->owner;
719
720
		while($object = $object->getParent()) {
721
			$ancestors->push($object);
722
		}
723
724
		return $ancestors;
725
	}
726
727
	/**
728
	 * Returns a human-readable, flattened representation of the path to the object, using its {@link Title} attribute.
729
	 *
730
	 * @param string $separator
731
	 * @return string
732
	 */
733
	public function getBreadcrumbs($separator = ' &raquo; ') {
734
		$crumbs = array();
735
		$ancestors = array_reverse($this->owner->getAncestors()->toArray());
736
		foreach($ancestors as $ancestor) $crumbs[] = $ancestor->Title;
737
		$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...
738
		return implode($separator, $crumbs);
739
	}
740
741
	/**
742
	 * Get the next node in the tree of the type. If there is no instance of the className descended from this node,
743
	 * then search the parents.
744
	 *
745
	 * @todo Write!
746
	 *
747
	 * @param string     $className Class name of the node to find
748
	 * @param DataObject $afterNode Used for recursive calls to this function
749
	 * @return DataObject
750
	 */
751
	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...
752
		return null;
753
	}
754
755
	/**
756
	 * Get the next node in the tree of the type. If there is no instance of the className descended from this node,
757
	 * then search the parents.
758
	 * @param string     $className Class name of the node to find.
759
	 * @param string|int $root      ID/ClassName of the node to limit the search to
760
	 * @param DataObject $afterNode Used for recursive calls to this function
761
	 * @return DataObject
762
	 */
763
	public function naturalNext($className = null, $root = 0, $afterNode = null ) {
764
		// If this node is not the node we are searching from, then we can possibly return this node as a solution
765
		if($afterNode && $afterNode->ID != $this->owner->ID) {
766
			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...
767
				return $this->owner;
768
			}
769
		}
770
771
		$nextNode = null;
772
		$baseClass = ClassInfo::baseDataClass($this->owner->class);
773
774
		$children = $baseClass::get()
775
			->filter('ParentID', (int)$this->owner->ID)
776
			->sort('"Sort"', 'ASC');
777
		if ($afterNode) {
778
			$children = $children->filter('Sort:GreaterThan', $afterNode->Sort);
779
		}
780
781
		// Try all the siblings of this node after the given node
782
		/*if( $siblings = DataObject::get( ClassInfo::baseDataClass($this->owner->class),
783
		"\"ParentID\"={$this->owner->ParentID}" . ( $afterNode ) ? "\"Sort\"
784
		> {$afterNode->Sort}" : "" , '\"Sort\" ASC' ) ) $searchNodes->merge( $siblings );*/
785
786
		if($children) {
787
			foreach($children as $node) {
788
				if($nextNode = $node->naturalNext($className, $node->ID, $this->owner)) {
789
					break;
790
				}
791
			}
792
793
			if($nextNode) {
794
				return $nextNode;
795
			}
796
		}
797
798
		// if this is not an instance of the root class or has the root id, search the parent
799
		if(!(is_numeric($root) && $root == $this->owner->ID || $root == $this->owner->class)
800
				&& ($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...
801
802
			return $parent->naturalNext( $className, $root, $this->owner );
803
		}
804
805
		return null;
806
	}
807
808
	/**
809
	 * Flush all Hierarchy caches:
810
	 * - Children (instance)
811
	 * - NumChildren (instance)
812
	 * - Marked (global)
813
	 * - Expanded (global)
814
	 * - TreeOpened (global)
815
	 */
816
	public function flushCache() {
817
		$this->_cache_children = null;
818
		$this->_cache_numChildren = null;
819
		self::$marked = array();
820
		self::$expanded = array();
821
		self::$treeOpened = array();
822
	}
823
824
	/**
825
	 * Reset global Hierarchy caches:
826
	 * - Marked
827
	 * - Expanded
828
	 * - TreeOpened
829
	 */
830
	public static function reset() {
831
		self::$marked = array();
832
		self::$expanded = array();
833
		self::$treeOpened = array();
834
	}
835
836
}
837