Total Complexity | 71 |
Total Lines | 553 |
Duplicated Lines | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
Complex classes like Hierarchy often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Hierarchy, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
29 | class Hierarchy extends DataExtension |
||
30 | { |
||
31 | /** |
||
32 | * The lower bounds for the amount of nodes to mark. If set, the logic will expand nodes until it reaches at least |
||
33 | * this number, and then stops. Root nodes will always show regardless of this setting. Further nodes can be |
||
34 | * lazy-loaded via ajax. This isn't a hard limit. Example: On a value of 10, with 20 root nodes, each having 30 |
||
35 | * children, the actual node count will be 50 (all root nodes plus first expanded child). |
||
36 | * |
||
37 | * @config |
||
38 | * @var int |
||
39 | */ |
||
40 | private static $node_threshold_total = 50; |
||
41 | |||
42 | /** |
||
43 | * Limit on the maximum children a specific node can display. Serves as a hard limit to avoid exceeding available |
||
44 | * server resources in generating the tree, and browser resources in rendering it. Nodes with children exceeding |
||
45 | * this value typically won't display any children, although this is configurable through the $nodeCountCallback |
||
46 | * parameter in {@link getChildrenAsUL()}. "Root" nodes will always show all children, regardless of this setting. |
||
47 | * |
||
48 | * @config |
||
49 | * @var int |
||
50 | */ |
||
51 | private static $node_threshold_leaf = 250; |
||
52 | |||
53 | /** |
||
54 | * A list of classnames to exclude from display in both the CMS and front end |
||
55 | * displays. ->Children() and ->AllChildren affected. |
||
56 | * Especially useful for big sets of pages like listings |
||
57 | * If you use this, and still need the classes to be editable |
||
58 | * then add a model admin for the class |
||
59 | * Note: Does not filter subclasses (non-inheriting) |
||
60 | * |
||
61 | * @var array |
||
62 | * @config |
||
63 | */ |
||
64 | private static $hide_from_hierarchy = []; |
||
65 | |||
66 | /** |
||
67 | * A list of classnames to exclude from display in the page tree views of the CMS, |
||
68 | * unlike $hide_from_hierarchy above which effects both CMS and front end. |
||
69 | * Especially useful for big sets of pages like listings |
||
70 | * If you use this, and still need the classes to be editable |
||
71 | * then add a model admin for the class |
||
72 | * Note: Does not filter subclasses (non-inheriting) |
||
73 | * |
||
74 | * @var array |
||
75 | * @config |
||
76 | */ |
||
77 | private static $hide_from_cms_tree = []; |
||
78 | |||
79 | /** |
||
80 | * Used to enable or disable the prepopulation of the numchildren cache. |
||
81 | * Defaults to true. |
||
82 | * |
||
83 | * @config |
||
84 | * @var boolean |
||
85 | */ |
||
86 | private static $prepopulate_numchildren_cache = true; |
||
87 | |||
88 | /** |
||
89 | * Prevent virtual page virtualising these fields |
||
90 | * |
||
91 | * @config |
||
92 | * @var array |
||
93 | */ |
||
94 | private static $non_virtual_fields = [ |
||
95 | '_cache_children', |
||
96 | ]; |
||
97 | |||
98 | /** |
||
99 | * A cache used by numChildren(). |
||
100 | * Clear through {@link flushCache()}. |
||
101 | * version (int)0 means not on this stage. |
||
102 | * |
||
103 | * @var array |
||
104 | */ |
||
105 | protected static $cache_numChildren = []; |
||
106 | |||
107 | public static function get_extra_config($class, $extension, $args) |
||
108 | { |
||
109 | return [ |
||
110 | 'has_one' => ['Parent' => $class] |
||
111 | ]; |
||
112 | } |
||
113 | |||
114 | /** |
||
115 | * Validate the owner object - check for existence of infinite loops. |
||
116 | * |
||
117 | * @param ValidationResult $validationResult |
||
118 | */ |
||
119 | public function validate(ValidationResult $validationResult) |
||
120 | { |
||
121 | // The object is new, won't be looping. |
||
122 | /** @var DataObject|Hierarchy $owner */ |
||
123 | $owner = $this->owner; |
||
124 | if (!$owner->ID) { |
||
125 | return; |
||
126 | } |
||
127 | // The object has no parent, won't be looping. |
||
128 | if (!$owner->ParentID) { |
||
129 | return; |
||
130 | } |
||
131 | // The parent has not changed, skip the check for performance reasons. |
||
132 | if (!$owner->isChanged('ParentID')) { |
||
133 | return; |
||
134 | } |
||
135 | |||
136 | // Walk the hierarchy upwards until we reach the top, or until we reach the originating node again. |
||
137 | $node = $owner; |
||
138 | while ($node && $node->ParentID) { |
||
139 | if ((int)$node->ParentID === (int)$owner->ID) { |
||
140 | // Hierarchy is looping. |
||
141 | $validationResult->addError( |
||
142 | _t( |
||
143 | __CLASS__ . '.InfiniteLoopNotAllowed', |
||
144 | 'Infinite loop found within the "{type}" hierarchy. Please change the parent to resolve this', |
||
145 | 'First argument is the class that makes up the hierarchy.', |
||
146 | ['type' => get_class($owner)] |
||
147 | ), |
||
148 | 'bad', |
||
149 | 'INFINITE_LOOP' |
||
150 | ); |
||
151 | break; |
||
152 | } |
||
153 | $node = $node->Parent(); |
||
154 | } |
||
155 | } |
||
156 | |||
157 | |||
158 | /** |
||
159 | * Get a list of this DataObject's and all it's descendants IDs. |
||
160 | * |
||
161 | * @return int[] |
||
162 | */ |
||
163 | public function getDescendantIDList() |
||
164 | { |
||
165 | $idList = []; |
||
166 | $this->loadDescendantIDListInto($idList); |
||
167 | return $idList; |
||
168 | } |
||
169 | |||
170 | /** |
||
171 | * Get a list of this DataObject's and all it's descendants ID, and put them in $idList. |
||
172 | * |
||
173 | * @param array $idList Array to put results in. |
||
174 | * @param DataObject|Hierarchy $node |
||
175 | */ |
||
176 | protected function loadDescendantIDListInto(&$idList, $node = null) |
||
177 | { |
||
178 | if (!$node) { |
||
179 | $node = $this->owner; |
||
180 | } |
||
181 | $children = $node->AllChildren(); |
||
182 | foreach ($children as $child) { |
||
183 | if (!in_array($child->ID, $idList)) { |
||
184 | $idList[] = $child->ID; |
||
185 | $this->loadDescendantIDListInto($idList, $child); |
||
186 | } |
||
187 | } |
||
188 | } |
||
189 | |||
190 | /** |
||
191 | * Get the children for this DataObject filtered by canView() |
||
192 | * |
||
193 | * @return SS_List |
||
194 | */ |
||
195 | public function Children() |
||
196 | { |
||
197 | $children = $this->owner->_cache_children; |
||
198 | if ($children) { |
||
199 | return $children; |
||
200 | } |
||
201 | |||
202 | $children = $this |
||
203 | ->owner |
||
204 | ->stageChildren(false) |
||
205 | ->filterByCallback(function (DataObject $record) { |
||
206 | return $record->canView(); |
||
207 | }); |
||
208 | $this->owner->_cache_children = $children; |
||
209 | return $children; |
||
210 | } |
||
211 | |||
212 | /** |
||
213 | * Return all children, including those 'not in menus'. |
||
214 | * |
||
215 | * @return DataList |
||
216 | */ |
||
217 | public function AllChildren() |
||
218 | { |
||
219 | return $this->owner->stageChildren(true); |
||
220 | } |
||
221 | |||
222 | /** |
||
223 | * Return all children, including those that have been deleted but are still in live. |
||
224 | * - Deleted children will be marked as "DeletedFromStage" |
||
225 | * - Added children will be marked as "AddedToStage" |
||
226 | * - Modified children will be marked as "ModifiedOnStage" |
||
227 | * - Everything else has "SameOnStage" set, as an indicator that this information has been looked up. |
||
228 | * |
||
229 | * @return ArrayList |
||
230 | */ |
||
231 | public function AllChildrenIncludingDeleted() |
||
232 | { |
||
233 | /** @var DataObject|Hierarchy|Versioned $owner */ |
||
234 | $owner = $this->owner; |
||
235 | $stageChildren = $owner->stageChildren(true); |
||
236 | |||
237 | // Add live site content that doesn't exist on the stage site, if required. |
||
238 | if ($owner->hasExtension(Versioned::class) && $owner->hasStages()) { |
||
239 | // Next, go through the live children. Only some of these will be listed |
||
240 | $liveChildren = $owner->liveChildren(true, true); |
||
241 | if ($liveChildren) { |
||
242 | $merged = new ArrayList(); |
||
243 | $merged->merge($stageChildren); |
||
244 | $merged->merge($liveChildren); |
||
245 | $stageChildren = $merged; |
||
246 | } |
||
247 | } |
||
248 | $owner->extend("augmentAllChildrenIncludingDeleted", $stageChildren); |
||
249 | return $stageChildren; |
||
250 | } |
||
251 | |||
252 | /** |
||
253 | * Return all the children that this page had, including pages that were deleted from both stage & live. |
||
254 | * |
||
255 | * @return DataList |
||
256 | * @throws Exception |
||
257 | */ |
||
258 | public function AllHistoricalChildren() |
||
259 | { |
||
260 | /** @var DataObject|Versioned|Hierarchy $owner */ |
||
261 | $owner = $this->owner; |
||
262 | if (!$owner->hasExtension(Versioned::class) || !$owner->hasStages()) { |
||
263 | throw new Exception( |
||
264 | 'Hierarchy->AllHistoricalChildren() only works with Versioned extension applied with staging' |
||
265 | ); |
||
266 | } |
||
267 | |||
268 | $baseTable = $owner->baseTable(); |
||
269 | $parentIDColumn = $owner->getSchema()->sqlColumnForField($owner, 'ParentID'); |
||
270 | return Versioned::get_including_deleted( |
||
271 | $owner->baseClass(), |
||
272 | [ $parentIDColumn => $owner->ID ], |
||
273 | "\"{$baseTable}\".\"ID\" ASC" |
||
274 | ); |
||
275 | } |
||
276 | |||
277 | /** |
||
278 | * Return the number of children that this page ever had, including pages that were deleted. |
||
279 | * |
||
280 | * @return int |
||
281 | */ |
||
282 | public function numHistoricalChildren() |
||
283 | { |
||
284 | return $this->AllHistoricalChildren()->count(); |
||
285 | } |
||
286 | |||
287 | /** |
||
288 | * Return the number of direct children. By default, values are cached after the first invocation. Can be |
||
289 | * augmented by {@link augmentNumChildrenCountQuery()}. |
||
290 | * |
||
291 | * @param bool $cache Whether to retrieve values from cache |
||
292 | * @return int |
||
293 | */ |
||
294 | public function numChildren($cache = true) |
||
295 | { |
||
296 | |||
297 | $baseClass = $this->owner->baseClass(); |
||
298 | $cacheType = 'numChildren'; |
||
299 | $id = $this->owner->ID; |
||
300 | |||
301 | // cached call |
||
302 | if ($cache) { |
||
303 | if (isset(self::$cache_numChildren[$baseClass][$cacheType][$id])) { |
||
304 | return self::$cache_numChildren[$baseClass][$cacheType][$id]; |
||
305 | } elseif (isset(self::$cache_numChildren[$baseClass][$cacheType]['_complete'])) { |
||
306 | // If the cache is complete and we didn't find our ID in the cache, it means this object is childless. |
||
307 | return 0; |
||
308 | } |
||
309 | } |
||
310 | |||
311 | // We call stageChildren(), because Children() has canView() filtering |
||
312 | $numChildren = (int)$this->owner->stageChildren(true)->Count(); |
||
313 | |||
314 | // Save if caching |
||
315 | if ($cache) { |
||
316 | self::$cache_numChildren[$baseClass][$cacheType][$id] = $numChildren; |
||
317 | } |
||
318 | |||
319 | return $numChildren; |
||
320 | } |
||
321 | |||
322 | /** |
||
323 | * Pre-populate any appropriate caches prior to rendering a tree. |
||
324 | * This is used to allow for the efficient rendering of tree views, notably in the CMS. |
||
325 | * In the case of Hierarchy, it caches numChildren values. Other extensions can provide an |
||
326 | * onPrepopulateTreeDataCache(DataList $recordList = null, array $options) methods to hook |
||
327 | * into this event as well. |
||
328 | * |
||
329 | * @param DataList|array $recordList The list of records to prepopulate caches for. Null for all records. |
||
330 | * @param array $options A map of hints about what should be cached. "numChildrenMethod" and |
||
331 | * "childrenMethod" are allowed keys. |
||
332 | */ |
||
333 | public function prepopulateTreeDataCache($recordList = null, array $options = []) |
||
334 | { |
||
335 | if (empty($options['numChildrenMethod']) || $options['numChildrenMethod'] === 'numChildren') { |
||
336 | $idList = is_array($recordList) ? $recordList : |
||
337 | ($recordList instanceof DataList ? $recordList->column('ID') : null); |
||
338 | self::prepopulate_numchildren_cache($this->getHierarchyBaseClass(), $idList); |
||
339 | } |
||
340 | |||
341 | $this->owner->extend('onPrepopulateTreeDataCache', $recordList, $options); |
||
342 | } |
||
343 | |||
344 | /** |
||
345 | * Pre-populate the cache for Versioned::get_versionnumber_by_stage() for |
||
346 | * a list of record IDs, for more efficient database querying. If $idList |
||
347 | * is null, then every record will be pre-cached. |
||
348 | * |
||
349 | * @param string $baseClass |
||
350 | * @param array $idList |
||
351 | */ |
||
352 | public static function prepopulate_numchildren_cache($baseClass, $idList = null) |
||
353 | { |
||
354 | if (!Config::inst()->get(static::class, 'prepopulate_numchildren_cache')) { |
||
355 | return; |
||
356 | } |
||
357 | |||
358 | /** @var Versioned|DataObject $singleton */ |
||
359 | $dummyObject = DataObject::singleton($baseClass); |
||
360 | $baseTable = $dummyObject->baseTable(); |
||
361 | |||
362 | $idColumn = Convert::symbol2sql("{$baseTable}.ID"); |
||
363 | |||
364 | // Get the stageChildren() result of a dummy object and break down into a generic query |
||
365 | $query = $dummyObject->stageChildren(true, true)->dataQuery()->query(); |
||
366 | |||
367 | // optional ID-list filter |
||
368 | if ($idList) { |
||
369 | // Validate the ID list |
||
370 | foreach ($idList as $id) { |
||
371 | if (!is_numeric($id)) { |
||
372 | throw new \InvalidArgumentException( |
||
373 | "Bad ID passed to Versioned::prepopulate_numchildren_cache() in \$idList: " . $id |
||
374 | ); |
||
375 | } |
||
376 | } |
||
377 | $query->addWhere(['"ParentID" IN (' . DB::placeholders($idList) . ')' => $idList]); |
||
378 | } |
||
379 | |||
380 | $query->setOrderBy(null); |
||
381 | |||
382 | $query->setSelect([ |
||
383 | '"ParentID"', |
||
384 | "COUNT(DISTINCT $idColumn) AS \"NumChildren\"", |
||
385 | ]); |
||
386 | $query->setGroupBy([Convert::symbol2sql("ParentID")]); |
||
387 | |||
388 | $numChildren = $query->execute()->map(); |
||
389 | self::$cache_numChildren[$baseClass]['numChildren'] = $numChildren; |
||
390 | if (!$idList) { |
||
391 | // If all objects are being cached, mark this cache as complete |
||
392 | // to avoid counting children of childless object. |
||
393 | self::$cache_numChildren[$baseClass]['numChildren']['_complete'] = true; |
||
394 | } |
||
395 | } |
||
396 | |||
397 | /** |
||
398 | * Checks if we're on a controller where we should filter. ie. Are we loading the SiteTree? |
||
399 | * |
||
400 | * @return bool |
||
401 | */ |
||
402 | public function showingCMSTree() |
||
410 | } |
||
411 | |||
412 | /** |
||
413 | * Find the first class in the inheritance chain that has Hierarchy extension applied |
||
414 | * |
||
415 | * @return string |
||
416 | */ |
||
417 | private function getHierarchyBaseClass(): string |
||
418 | { |
||
419 | $ancestry = ClassInfo::ancestry($this->owner); |
||
420 | $ancestorClass = array_shift($ancestry); |
||
421 | while ($ancestorClass && !Extensible::has_extension($ancestorClass, self::class)) { |
||
422 | $ancestorClass = array_shift($ancestry); |
||
423 | } |
||
424 | |||
425 | return $ancestorClass; |
||
426 | } |
||
427 | |||
428 | /** |
||
429 | * Return children in the stage site. |
||
430 | * |
||
431 | * @param bool $showAll Include all of the elements, even those not shown in the menus. Only applicable when |
||
432 | * extension is applied to {@link SiteTree}. |
||
433 | * @param bool $skipParentIDFilter Set to true to suppress the ParentID and ID where statements. |
||
434 | * @return DataList |
||
435 | */ |
||
436 | public function stageChildren($showAll = false, $skipParentIDFilter = false) |
||
437 | { |
||
438 | /** @var DataObject|Hierarchy $owner */ |
||
439 | $owner = $this->owner; |
||
440 | $hideFromHierarchy = $owner->config()->hide_from_hierarchy; |
||
441 | $hideFromCMSTree = $owner->config()->hide_from_cms_tree; |
||
442 | $class = $this->getHierarchyBaseClass(); |
||
443 | |||
444 | $schema = DataObject::getSchema(); |
||
445 | $tableForParentID = $schema->tableForField($class, 'ParentID'); |
||
446 | $tableForID = $schema->tableForField($class, 'ID'); |
||
447 | |||
448 | $staged = DataObject::get($class)->where(sprintf( |
||
449 | '%s.%s <> %s.%s', |
||
450 | Convert::symbol2sql($tableForParentID), |
||
451 | Convert::symbol2sql("ParentID"), |
||
452 | Convert::symbol2sql($tableForID), |
||
453 | Convert::symbol2sql("ID") |
||
454 | )); |
||
455 | |||
456 | if (!$skipParentIDFilter) { |
||
457 | // There's no filtering by ID if we don't have an ID. |
||
458 | $staged = $staged->filter('ParentID', (int)$this->owner->ID); |
||
459 | } |
||
460 | |||
461 | if ($hideFromHierarchy) { |
||
462 | $staged = $staged->exclude('ClassName', $hideFromHierarchy); |
||
463 | } |
||
464 | if ($hideFromCMSTree && $this->showingCMSTree()) { |
||
465 | $staged = $staged->exclude('ClassName', $hideFromCMSTree); |
||
466 | } |
||
467 | if (!$showAll && DataObject::getSchema()->fieldSpec($this->owner, 'ShowInMenus')) { |
||
468 | $staged = $staged->filter('ShowInMenus', 1); |
||
469 | } |
||
470 | $this->owner->extend("augmentStageChildren", $staged, $showAll); |
||
471 | return $staged; |
||
472 | } |
||
473 | |||
474 | /** |
||
475 | * Return children in the live site, if it exists. |
||
476 | * |
||
477 | * @param bool $showAll Include all of the elements, even those not shown in the menus. Only |
||
478 | * applicable when extension is applied to {@link SiteTree}. |
||
479 | * @param bool $onlyDeletedFromStage Only return items that have been deleted from stage |
||
480 | * @return DataList |
||
481 | * @throws Exception |
||
482 | */ |
||
483 | public function liveChildren($showAll = false, $onlyDeletedFromStage = false) |
||
484 | { |
||
485 | /** @var Versioned|DataObject|Hierarchy $owner */ |
||
486 | $owner = $this->owner; |
||
487 | if (!$owner->hasExtension(Versioned::class) || !$owner->hasStages()) { |
||
488 | throw new Exception('Hierarchy->liveChildren() only works with Versioned extension applied with staging'); |
||
489 | } |
||
490 | |||
491 | $hideFromHierarchy = $owner->config()->hide_from_hierarchy; |
||
492 | $hideFromCMSTree = $owner->config()->hide_from_cms_tree; |
||
493 | $children = DataObject::get($this->getHierarchyBaseClass()) |
||
494 | ->filter('ParentID', (int)$owner->ID) |
||
495 | ->exclude('ID', (int)$owner->ID) |
||
496 | ->setDataQueryParam([ |
||
497 | 'Versioned.mode' => $onlyDeletedFromStage ? 'stage_unique' : 'stage', |
||
498 | 'Versioned.stage' => 'Live' |
||
499 | ]); |
||
500 | if ($hideFromHierarchy) { |
||
501 | $children = $children->exclude('ClassName', $hideFromHierarchy); |
||
502 | } |
||
503 | if ($hideFromCMSTree && $this->showingCMSTree()) { |
||
504 | $children = $children->exclude('ClassName', $hideFromCMSTree); |
||
505 | } |
||
506 | if (!$showAll && DataObject::getSchema()->fieldSpec($owner, 'ShowInMenus')) { |
||
507 | $children = $children->filter('ShowInMenus', 1); |
||
508 | } |
||
509 | |||
510 | return $children; |
||
511 | } |
||
512 | |||
513 | /** |
||
514 | * Get this object's parent, optionally filtered by an SQL clause. If the clause doesn't match the parent, nothing |
||
515 | * is returned. |
||
516 | * |
||
517 | * @param string $filter |
||
518 | * @return DataObject |
||
519 | */ |
||
520 | public function getParent($filter = null) |
||
531 | ]); |
||
532 | } |
||
533 | |||
534 | /** |
||
535 | * Return all the parents of this class in a set ordered from the closest to furtherest parent. |
||
536 | * |
||
537 | * @param bool $includeSelf |
||
538 | * @return ArrayList |
||
539 | */ |
||
540 | public function getAncestors($includeSelf = false) |
||
541 | { |
||
542 | $ancestors = new ArrayList(); |
||
543 | $object = $this->owner; |
||
544 | |||
545 | if ($includeSelf) { |
||
546 | $ancestors->push($object); |
||
547 | } |
||
548 | while ($object = $object->getParent()) { |
||
549 | $ancestors->push($object); |
||
550 | } |
||
551 | |||
552 | return $ancestors; |
||
553 | } |
||
554 | |||
555 | /** |
||
556 | * Returns a human-readable, flattened representation of the path to the object, using its {@link Title} attribute. |
||
557 | * |
||
558 | * @param string $separator |
||
559 | * @return string |
||
560 | */ |
||
561 | public function getBreadcrumbs($separator = ' » ') |
||
571 | } |
||
572 | |||
573 | /** |
||
574 | * Flush all Hierarchy caches: |
||
575 | * - Children (instance) |
||
576 | * - NumChildren (instance) |
||
577 | */ |
||
578 | public function flushCache() |
||
579 | { |
||
582 | } |
||
583 | } |
||
584 |
The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g.
excluded_paths: ["lib/*"]
, you can move it to the dependency path list as follows:For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths