Hierarchy   F
last analyzed

Complexity

Total Complexity 68

Size/Duplication

Total Lines 533
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 179
dl 0
loc 533
rs 2.96
c 0
b 0
f 0
wmc 68

19 Methods

Rating   Name   Duplication   Size   Complexity  
A Children() 0 15 2
B validate() 0 35 7
A AllHistoricalChildren() 0 16 3
A get_extra_config() 0 4 1
A loadDescendantIDListInto() 0 10 4
A AllChildren() 0 3 1
A getDescendantIDList() 0 5 1
A numHistoricalChildren() 0 3 1
A AllChildrenIncludingDeleted() 0 19 4
A numChildren() 0 26 5
B prepopulate_numchildren_cache() 0 43 6
A showingCMSTree() 0 8 4
A prepopulateTreeDataCache() 0 9 5
A getParent() 0 11 2
B liveChildren() 0 28 9
A getBreadcrumbs() 0 10 2
A getAncestors() 0 13 3
A flushCache() 0 4 1
B stageChildren() 0 30 7

How to fix   Complexity   

Complex Class

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
2
3
namespace SilverStripe\ORM\Hierarchy;
4
5
use SilverStripe\Admin\LeftAndMain;
0 ignored issues
show
Bug introduced by
The type SilverStripe\Admin\LeftAndMain was not found. Maybe you did not declare it correctly or list all dependencies?

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:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use SilverStripe\Control\Controller;
7
use SilverStripe\ORM\DataList;
8
use SilverStripe\ORM\SS_List;
9
use SilverStripe\ORM\ValidationResult;
10
use SilverStripe\ORM\ArrayList;
11
use SilverStripe\ORM\DataObject;
12
use SilverStripe\ORM\DataExtension;
13
use SilverStripe\ORM\DB;
14
use SilverStripe\Versioned\Versioned;
15
use SilverStripe\Core\Config\Config;
16
use SilverStripe\Core\Convert;
17
use Exception;
18
19
/**
20
 * DataObjects that use the Hierarchy extension can be be organised as a hierarchy, with children and parents. The most
21
 * obvious example of this is SiteTree.
22
 *
23
 * @property int $ParentID
24
 * @property DataObject|Hierarchy $owner
25
 * @method DataObject Parent()
26
 */
27
class Hierarchy extends DataExtension
28
{
29
    /**
30
     * The lower bounds for the amount of nodes to mark. If set, the logic will expand nodes until it reaches at least
31
     * this number, and then stops. Root nodes will always show regardless of this settting. Further nodes can be
32
     * lazy-loaded via ajax. This isn't a hard limit. Example: On a value of 10, with 20 root nodes, each having 30
33
     * children, the actual node count will be 50 (all root nodes plus first expanded child).
34
     *
35
     * @config
36
     * @var int
37
     */
38
    private static $node_threshold_total = 50;
0 ignored issues
show
introduced by
The private property $node_threshold_total is not used, and could be removed.
Loading history...
39
40
    /**
41
     * Limit on the maximum children a specific node can display. Serves as a hard limit to avoid exceeding available
42
     * server resources in generating the tree, and browser resources in rendering it. Nodes with children exceeding
43
     * this value typically won't display any children, although this is configurable through the $nodeCountCallback
44
     * parameter in {@link getChildrenAsUL()}. "Root" nodes will always show all children, regardless of this setting.
45
     *
46
     * @config
47
     * @var int
48
     */
49
    private static $node_threshold_leaf = 250;
0 ignored issues
show
introduced by
The private property $node_threshold_leaf is not used, and could be removed.
Loading history...
50
51
    /**
52
     * A list of classnames to exclude from display in both the CMS and front end
53
     * displays. ->Children() and ->AllChildren affected.
54
     * Especially useful for big sets of pages like listings
55
     * If you use this, and still need the classes to be editable
56
     * then add a model admin for the class
57
     * Note: Does not filter subclasses (non-inheriting)
58
     *
59
     * @var array
60
     * @config
61
     */
62
    private static $hide_from_hierarchy = array();
63
64
    /**
65
     * A list of classnames to exclude from display in the page tree views of the CMS,
66
     * unlike $hide_from_hierarchy above which effects both CMS and front end.
67
     * Especially useful for big sets of pages like listings
68
     * If you use this, and still need the classes to be editable
69
     * then add a model admin for the class
70
     * Note: Does not filter subclasses (non-inheriting)
71
     *
72
     * @var array
73
     * @config
74
     */
75
    private static $hide_from_cms_tree = array();
76
77
    /**
78
     * Used to enable or disable the prepopulation of the numchildren cache.
79
     * Defaults to true.
80
     *
81
     * @config
82
     * @var boolean
83
     */
84
    private static $prepopulate_numchildren_cache = true;
0 ignored issues
show
introduced by
The private property $prepopulate_numchildren_cache is not used, and could be removed.
Loading history...
85
86
    /**
87
     * Prevent virtual page virtualising these fields
88
     *
89
     * @config
90
     * @var array
91
     */
92
    private static $non_virtual_fields = [
0 ignored issues
show
introduced by
The private property $non_virtual_fields is not used, and could be removed.
Loading history...
93
        '_cache_children',
94
    ];
95
96
    /**
97
     * A cache used by numChildren().
98
     * Clear through {@link flushCache()}.
99
     * version (int)0 means not on this stage.
100
     *
101
     * @var array
102
     */
103
    protected static $cache_numChildren = [];
104
105
    public static function get_extra_config($class, $extension, $args)
0 ignored issues
show
Unused Code introduced by
The parameter $args is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

105
    public static function get_extra_config($class, $extension, /** @scrutinizer ignore-unused */ $args)

This check looks for 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 $extension is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

105
    public static function get_extra_config($class, /** @scrutinizer ignore-unused */ $extension, $args)

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

Loading history...
106
    {
107
        return array(
108
            'has_one' => array('Parent' => $class)
109
        );
110
    }
111
112
    /**
113
     * Validate the owner object - check for existence of infinite loops.
114
     *
115
     * @param ValidationResult $validationResult
116
     */
117
    public function validate(ValidationResult $validationResult)
118
    {
119
        // The object is new, won't be looping.
120
        /** @var DataObject|Hierarchy $owner */
121
        $owner = $this->owner;
122
        if (!$owner->ID) {
0 ignored issues
show
Bug Best Practice introduced by
The property ID does not exist on SilverStripe\ORM\Hierarchy\Hierarchy. Did you maybe forget to declare it?
Loading history...
123
            return;
124
        }
125
        // The object has no parent, won't be looping.
126
        if (!$owner->ParentID) {
0 ignored issues
show
Bug Best Practice introduced by
The property ParentID does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
127
            return;
128
        }
129
        // The parent has not changed, skip the check for performance reasons.
130
        if (!$owner->isChanged('ParentID')) {
0 ignored issues
show
Bug introduced by
The method isChanged() does not exist on SilverStripe\ORM\Hierarchy\Hierarchy. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

130
        if (!$owner->/** @scrutinizer ignore-call */ isChanged('ParentID')) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
131
            return;
132
        }
133
134
        // Walk the hierarchy upwards until we reach the top, or until we reach the originating node again.
135
        $node = $owner;
136
        while ($node && $node->ParentID) {
137
            if ((int)$node->ParentID === (int)$owner->ID) {
138
                // Hierarchy is looping.
139
                $validationResult->addError(
140
                    _t(
141
                        __CLASS__ . '.InfiniteLoopNotAllowed',
142
                        'Infinite loop found within the "{type}" hierarchy. Please change the parent to resolve this',
143
                        'First argument is the class that makes up the hierarchy.',
144
                        array('type' => get_class($owner))
145
                    ),
146
                    'bad',
147
                    'INFINITE_LOOP'
148
                );
149
                break;
150
            }
151
            $node = $node->Parent();
0 ignored issues
show
Bug introduced by
The method Parent() does not exist on SilverStripe\ORM\DataObject. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

151
            /** @scrutinizer ignore-call */ 
152
            $node = $node->Parent();
Loading history...
152
        }
153
    }
154
155
156
    /**
157
     * Get a list of this DataObject's and all it's descendants IDs.
158
     *
159
     * @return int[]
160
     */
161
    public function getDescendantIDList()
162
    {
163
        $idList = array();
164
        $this->loadDescendantIDListInto($idList);
165
        return $idList;
166
    }
167
168
    /**
169
     * Get a list of this DataObject's and all it's descendants ID, and put them in $idList.
170
     *
171
     * @param array $idList Array to put results in.
172
     * @param DataObject|Hierarchy $node
173
     */
174
    protected function loadDescendantIDListInto(&$idList, $node = null)
175
    {
176
        if (!$node) {
177
            $node = $this->owner;
178
        }
179
        $children = $node->AllChildren();
0 ignored issues
show
Bug introduced by
The method AllChildren() does not exist on SilverStripe\ORM\DataObject. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

179
        /** @scrutinizer ignore-call */ 
180
        $children = $node->AllChildren();
Loading history...
180
        foreach ($children as $child) {
181
            if (!in_array($child->ID, $idList)) {
182
                $idList[] = $child->ID;
183
                $this->loadDescendantIDListInto($idList, $child);
184
            }
185
        }
186
    }
187
188
    /**
189
     * Get the children for this DataObject filtered by canView()
190
     *
191
     * @return SS_List
192
     */
193
    public function Children()
194
    {
195
        $children = $this->owner->_cache_children;
0 ignored issues
show
Bug Best Practice introduced by
The property _cache_children does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
196
        if ($children) {
197
            return $children;
198
        }
199
200
        $children = $this
201
            ->owner
202
            ->stageChildren(false)
0 ignored issues
show
Bug introduced by
The method stageChildren() does not exist on SilverStripe\ORM\DataObject. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

202
            ->/** @scrutinizer ignore-call */ stageChildren(false)
Loading history...
203
            ->filterByCallback(function (DataObject $record) {
204
                return $record->canView();
205
            });
206
        $this->owner->_cache_children = $children;
0 ignored issues
show
Bug Best Practice introduced by
The property _cache_children does not exist on SilverStripe\ORM\DataObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
Bug Best Practice introduced by
The property _cache_children does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
207
        return $children;
208
    }
209
210
    /**
211
     * Return all children, including those 'not in menus'.
212
     *
213
     * @return DataList
214
     */
215
    public function AllChildren()
216
    {
217
        return $this->owner->stageChildren(true);
218
    }
219
220
    /**
221
     * Return all children, including those that have been deleted but are still in live.
222
     * - Deleted children will be marked as "DeletedFromStage"
223
     * - Added children will be marked as "AddedToStage"
224
     * - Modified children will be marked as "ModifiedOnStage"
225
     * - Everything else has "SameOnStage" set, as an indicator that this information has been looked up.
226
     *
227
     * @return ArrayList
228
     */
229
    public function AllChildrenIncludingDeleted()
230
    {
231
        /** @var DataObject|Hierarchy|Versioned $owner */
232
        $owner = $this->owner;
233
        $stageChildren = $owner->stageChildren(true);
234
235
        // Add live site content that doesn't exist on the stage site, if required.
236
        if ($owner->hasExtension(Versioned::class) && $owner->hasStages()) {
0 ignored issues
show
Bug introduced by
The method hasExtension() does not exist on SilverStripe\ORM\Hierarchy\Hierarchy. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

236
        if ($owner->/** @scrutinizer ignore-call */ hasExtension(Versioned::class) && $owner->hasStages()) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Bug introduced by
The method hasStages() does not exist on SilverStripe\ORM\Hierarchy\Hierarchy. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

236
        if ($owner->hasExtension(Versioned::class) && $owner->/** @scrutinizer ignore-call */ hasStages()) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Bug introduced by
The method hasStages() does not exist on SilverStripe\ORM\DataObject. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

236
        if ($owner->hasExtension(Versioned::class) && $owner->/** @scrutinizer ignore-call */ hasStages()) {
Loading history...
237
            // Next, go through the live children.  Only some of these will be listed
238
            $liveChildren = $owner->liveChildren(true, true);
0 ignored issues
show
Bug introduced by
The method liveChildren() does not exist on SilverStripe\ORM\DataObject. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

238
            /** @scrutinizer ignore-call */ 
239
            $liveChildren = $owner->liveChildren(true, true);
Loading history...
239
            if ($liveChildren) {
240
                $merged = new ArrayList();
241
                $merged->merge($stageChildren);
242
                $merged->merge($liveChildren);
243
                $stageChildren = $merged;
244
            }
245
        }
246
        $owner->extend("augmentAllChildrenIncludingDeleted", $stageChildren);
0 ignored issues
show
Bug introduced by
The method extend() does not exist on SilverStripe\ORM\Hierarchy\Hierarchy. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

246
        $owner->/** @scrutinizer ignore-call */ 
247
                extend("augmentAllChildrenIncludingDeleted", $stageChildren);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
247
        return $stageChildren;
248
    }
249
250
    /**
251
     * Return all the children that this page had, including pages that were deleted from both stage & live.
252
     *
253
     * @return DataList
254
     * @throws Exception
255
     */
256
    public function AllHistoricalChildren()
257
    {
258
        /** @var DataObject|Versioned|Hierarchy $owner */
259
        $owner = $this->owner;
260
        if (!$owner->hasExtension(Versioned::class) || !$owner->hasStages()) {
261
            throw new Exception(
262
                'Hierarchy->AllHistoricalChildren() only works with Versioned extension applied with staging'
263
            );
264
        }
265
266
        $baseTable = $owner->baseTable();
0 ignored issues
show
Bug introduced by
The method baseTable() does not exist on SilverStripe\ORM\Hierarchy\Hierarchy. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

266
        /** @scrutinizer ignore-call */ 
267
        $baseTable = $owner->baseTable();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
267
        $parentIDColumn = $owner->getSchema()->sqlColumnForField($owner, 'ParentID');
0 ignored issues
show
Bug introduced by
The method getSchema() does not exist on SilverStripe\ORM\Hierarchy\Hierarchy. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

267
        $parentIDColumn = $owner->/** @scrutinizer ignore-call */ getSchema()->sqlColumnForField($owner, 'ParentID');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Bug introduced by
It seems like $owner can also be of type SilverStripe\ORM\Hierarchy\Hierarchy; however, parameter $class of SilverStripe\ORM\DataObj...ma::sqlColumnForField() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

267
        $parentIDColumn = $owner->getSchema()->sqlColumnForField(/** @scrutinizer ignore-type */ $owner, 'ParentID');
Loading history...
268
        return Versioned::get_including_deleted(
269
            $owner->baseClass(),
0 ignored issues
show
Bug introduced by
The method baseClass() does not exist on SilverStripe\ORM\Hierarchy\Hierarchy. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

269
            $owner->/** @scrutinizer ignore-call */ 
270
                    baseClass(),

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
270
            [ $parentIDColumn => $owner->ID ],
0 ignored issues
show
Bug Best Practice introduced by
The property ID does not exist on SilverStripe\ORM\Hierarchy\Hierarchy. Did you maybe forget to declare it?
Loading history...
Bug introduced by
array($parentIDColumn => $owner->ID) of type array<string,integer> is incompatible with the type string expected by parameter $filter of SilverStripe\Versioned\V...get_including_deleted(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

270
            /** @scrutinizer ignore-type */ [ $parentIDColumn => $owner->ID ],
Loading history...
271
            "\"{$baseTable}\".\"ID\" ASC"
272
        );
273
    }
274
275
    /**
276
     * Return the number of children that this page ever had, including pages that were deleted.
277
     *
278
     * @return int
279
     */
280
    public function numHistoricalChildren()
281
    {
282
        return $this->AllHistoricalChildren()->count();
283
    }
284
285
    /**
286
     * Return the number of direct children. By default, values are cached after the first invocation. Can be
287
     * augumented by {@link augmentNumChildrenCountQuery()}.
288
     *
289
     * @param bool $cache Whether to retrieve values from cache
290
     * @return int
291
     */
292
    public function numChildren($cache = true)
293
    {
294
295
        $baseClass = $this->owner->baseClass();
296
        $cacheType = 'numChildren';
297
        $id = $this->owner->ID;
0 ignored issues
show
Bug Best Practice introduced by
The property ID does not exist on SilverStripe\ORM\Hierarchy\Hierarchy. Did you maybe forget to declare it?
Loading history...
298
299
        // cached call
300
        if ($cache) {
301
            if (isset(self::$cache_numChildren[$baseClass][$cacheType][$id])) {
302
                return self::$cache_numChildren[$baseClass][$cacheType][$id];
303
            } elseif (isset(self::$cache_numChildren[$baseClass][$cacheType]['_complete'])) {
304
                // If the cache is complete and we didn't find our ID in the cache, it means this object is childless.
305
                return 0;
306
            }
307
        }
308
309
        // We call stageChildren(), because Children() has canView() filtering
310
        $numChildren = (int)$this->owner->stageChildren(true)->Count();
311
312
        // Save if caching
313
        if ($cache) {
314
            self::$cache_numChildren[$baseClass][$cacheType][$id] = $numChildren;
315
        }
316
317
        return $numChildren;
318
    }
319
320
    /**
321
     * Pre-populate any appropriate caches prior to rendering a tree.
322
     * This is used to allow for the efficient rendering of tree views, notably in the CMS.
323
     * In the cace of Hierarchy, it caches numChildren values. Other extensions can provide an
324
     * onPrepopulateTreeDataCache(DataList $recordList = null, array $options) methods to hook
325
     * into this event as well.
326
     *
327
     * @param DataList|array $recordList The list of records to prepopulate caches for. Null for all records.
328
     * @param array $options A map of hints about what should be cached. "numChildrenMethod" and
329
     *                       "childrenMethod" are allowed keys.
330
     */
331
    public function prepopulateTreeDataCache($recordList = null, array $options = [])
332
    {
333
        if (empty($options['numChildrenMethod']) || $options['numChildrenMethod'] === 'numChildren') {
334
            $idList = is_array($recordList) ? $recordList :
335
                ($recordList instanceof DataList ? $recordList->column('ID') : null);
336
            self::prepopulate_numchildren_cache($this->owner->baseClass(), $idList);
337
        }
338
339
        $this->owner->extend('onPrepopulateTreeDataCache', $recordList, $options);
340
    }
341
342
    /**
343
     * Pre-populate the cache for Versioned::get_versionnumber_by_stage() for
344
     * a list of record IDs, for more efficient database querying.  If $idList
345
     * is null, then every record will be pre-cached.
346
     *
347
     * @param string $class
348
     * @param string $stage
349
     * @param array $idList
350
     */
351
    public static function prepopulate_numchildren_cache($baseClass, $idList = null)
352
    {
353
        if (!Config::inst()->get(static::class, 'prepopulate_numchildren_cache')) {
354
            return;
355
        }
356
357
        /** @var Versioned|DataObject $singleton */
358
        $dummyObject = DataObject::singleton($baseClass);
359
        $baseTable = $dummyObject->baseTable();
360
361
        $idColumn = Convert::symbol2sql("{$baseTable}.ID");
362
363
        // Get the stageChildren() result of a dummy object and break down into a generic query
364
        $query = $dummyObject->stageChildren(true, true)->dataQuery()->query();
365
366
        // optional ID-list filter
367
        if ($idList) {
368
            // Validate the ID list
369
            foreach ($idList as $id) {
370
                if (!is_numeric($id)) {
371
                    user_error(
372
                        "Bad ID passed to Versioned::prepopulate_numchildren_cache() in \$idList: " . $id,
373
                        E_USER_ERROR
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()
403
    {
404
        if (!Controller::has_curr() || !class_exists(LeftAndMain::class)) {
405
            return false;
406
        }
407
        $controller = Controller::curr();
408
        return $controller instanceof LeftAndMain
409
            && in_array($controller->getAction(), array("treeview", "listview", "getsubtree"));
410
    }
411
412
    /**
413
     * Return children in the stage site.
414
     *
415
     * @param bool $showAll Include all of the elements, even those not shown in the menus. Only applicable when
416
     *                      extension is applied to {@link SiteTree}.
417
     * @param bool $skipParentIDFilter Set to true to supress the ParentID and ID where statements.
418
     * @return DataList
419
     */
420
    public function stageChildren($showAll = false, $skipParentIDFilter = false)
421
    {
422
        $hideFromHierarchy = $this->owner->config()->hide_from_hierarchy;
0 ignored issues
show
Bug introduced by
The method config() does not exist on SilverStripe\ORM\Hierarchy\Hierarchy. Did you maybe mean get_extra_config()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

422
        $hideFromHierarchy = $this->owner->/** @scrutinizer ignore-call */ config()->hide_from_hierarchy;

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Bug Best Practice introduced by
The property hide_from_hierarchy does not exist on SilverStripe\Core\Config\Config_ForClass. Since you implemented __get, consider adding a @property annotation.
Loading history...
423
        $hideFromCMSTree = $this->owner->config()->hide_from_cms_tree;
0 ignored issues
show
Bug Best Practice introduced by
The property hide_from_cms_tree does not exist on SilverStripe\Core\Config\Config_ForClass. Since you implemented __get, consider adding a @property annotation.
Loading history...
424
        $baseClass = $this->owner->baseClass();
425
        $baseTable = $this->owner->baseTable();
426
        $staged = DataObject::get($baseClass)->where(sprintf(
427
            '%s.%s <> %s.%s',
428
            Convert::symbol2sql($baseTable),
429
            Convert::symbol2sql("ParentID"),
430
            Convert::symbol2sql($baseTable),
431
            Convert::symbol2sql("ID")
432
        ));
433
434
        if (!$skipParentIDFilter) {
435
            // There's no filtering by ID if we don't have an ID.
436
            $staged = $staged->filter('ParentID', (int)$this->owner->ID);
0 ignored issues
show
Bug Best Practice introduced by
The property ID does not exist on SilverStripe\ORM\Hierarchy\Hierarchy. Did you maybe forget to declare it?
Loading history...
437
        }
438
439
        if ($hideFromHierarchy) {
440
            $staged = $staged->exclude('ClassName', $hideFromHierarchy);
441
        }
442
        if ($hideFromCMSTree && $this->showingCMSTree()) {
443
            $staged = $staged->exclude('ClassName', $hideFromCMSTree);
444
        }
445
        if (!$showAll && DataObject::getSchema()->fieldSpec($this->owner, 'ShowInMenus')) {
0 ignored issues
show
Bug introduced by
It seems like $this->owner can also be of type SilverStripe\ORM\Hierarchy\Hierarchy; however, parameter $classOrInstance of SilverStripe\ORM\DataObjectSchema::fieldSpec() does only seem to accept SilverStripe\ORM\DataObject|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

445
        if (!$showAll && DataObject::getSchema()->fieldSpec(/** @scrutinizer ignore-type */ $this->owner, 'ShowInMenus')) {
Loading history...
446
            $staged = $staged->filter('ShowInMenus', 1);
447
        }
448
        $this->owner->extend("augmentStageChildren", $staged, $showAll);
449
        return $staged;
450
    }
451
452
    /**
453
     * Return children in the live site, if it exists.
454
     *
455
     * @param bool $showAll              Include all of the elements, even those not shown in the menus. Only
456
     *                                   applicable when extension is applied to {@link SiteTree}.
457
     * @param bool $onlyDeletedFromStage Only return items that have been deleted from stage
458
     * @return DataList
459
     * @throws Exception
460
     */
461
    public function liveChildren($showAll = false, $onlyDeletedFromStage = false)
462
    {
463
        /** @var Versioned|DataObject|Hierarchy $owner */
464
        $owner = $this->owner;
465
        if (!$owner->hasExtension(Versioned::class) || !$owner->hasStages()) {
466
            throw new Exception('Hierarchy->liveChildren() only works with Versioned extension applied with staging');
467
        }
468
469
        $hideFromHierarchy = $owner->config()->hide_from_hierarchy;
0 ignored issues
show
Bug Best Practice introduced by
The property hide_from_hierarchy does not exist on SilverStripe\Core\Config\Config_ForClass. Since you implemented __get, consider adding a @property annotation.
Loading history...
470
        $hideFromCMSTree = $owner->config()->hide_from_cms_tree;
0 ignored issues
show
Bug Best Practice introduced by
The property hide_from_cms_tree does not exist on SilverStripe\Core\Config\Config_ForClass. Since you implemented __get, consider adding a @property annotation.
Loading history...
471
        $children = DataObject::get($owner->baseClass())
472
            ->filter('ParentID', (int)$owner->ID)
0 ignored issues
show
Bug Best Practice introduced by
The property ID does not exist on SilverStripe\ORM\Hierarchy\Hierarchy. Did you maybe forget to declare it?
Loading history...
473
            ->exclude('ID', (int)$owner->ID)
474
            ->setDataQueryParam(array(
475
                'Versioned.mode' => $onlyDeletedFromStage ? 'stage_unique' : 'stage',
476
                'Versioned.stage' => 'Live'
477
            ));
478
        if ($hideFromHierarchy) {
479
            $children = $children->exclude('ClassName', $hideFromHierarchy);
480
        }
481
        if ($hideFromCMSTree && $this->showingCMSTree()) {
482
            $children = $children->exclude('ClassName', $hideFromCMSTree);
483
        }
484
        if (!$showAll && DataObject::getSchema()->fieldSpec($owner, 'ShowInMenus')) {
0 ignored issues
show
Bug introduced by
It seems like $owner can also be of type SilverStripe\ORM\Hierarchy\Hierarchy; however, parameter $classOrInstance of SilverStripe\ORM\DataObjectSchema::fieldSpec() does only seem to accept SilverStripe\ORM\DataObject|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

484
        if (!$showAll && DataObject::getSchema()->fieldSpec(/** @scrutinizer ignore-type */ $owner, 'ShowInMenus')) {
Loading history...
485
            $children = $children->filter('ShowInMenus', 1);
486
        }
487
488
        return $children;
489
    }
490
491
    /**
492
     * Get this object's parent, optionally filtered by an SQL clause. If the clause doesn't match the parent, nothing
493
     * is returned.
494
     *
495
     * @param string $filter
496
     * @return DataObject
497
     */
498
    public function getParent($filter = null)
499
    {
500
        $parentID = $this->owner->ParentID;
0 ignored issues
show
Bug Best Practice introduced by
The property ParentID does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
501
        if (empty($parentID)) {
502
            return null;
503
        }
504
        $baseClass = $this->owner->baseClass();
505
        $idSQL = $this->owner->getSchema()->sqlColumnForField($baseClass, 'ID');
506
        return DataObject::get_one($baseClass, [
507
            [$idSQL => $parentID],
508
            $filter
509
        ]);
510
    }
511
512
    /**
513
     * Return all the parents of this class in a set ordered from the closest to furtherest parent.
514
     *
515
     * @param bool $includeSelf
516
     * @return ArrayList
517
     */
518
    public function getAncestors($includeSelf = false)
519
    {
520
        $ancestors = new ArrayList();
521
        $object = $this->owner;
522
523
        if ($includeSelf) {
524
            $ancestors->push($object);
525
        }
526
        while ($object = $object->getParent()) {
0 ignored issues
show
Bug introduced by
The method getParent() does not exist on SilverStripe\ORM\DataObject. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

526
        while ($object = $object->/** @scrutinizer ignore-call */ getParent()) {
Loading history...
527
            $ancestors->push($object);
528
        }
529
530
        return $ancestors;
531
    }
532
533
    /**
534
     * Returns a human-readable, flattened representation of the path to the object, using its {@link Title} attribute.
535
     *
536
     * @param string $separator
537
     * @return string
538
     */
539
    public function getBreadcrumbs($separator = ' &raquo; ')
540
    {
541
        $crumbs = array();
542
        $ancestors = array_reverse($this->owner->getAncestors()->toArray());
0 ignored issues
show
Bug introduced by
The method getAncestors() does not exist on SilverStripe\ORM\DataObject. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

542
        $ancestors = array_reverse($this->owner->/** @scrutinizer ignore-call */ getAncestors()->toArray());
Loading history...
543
        /** @var DataObject $ancestor */
544
        foreach ($ancestors as $ancestor) {
545
            $crumbs[] = $ancestor->getTitle();
546
        }
547
        $crumbs[] = $this->owner->getTitle();
0 ignored issues
show
Bug introduced by
The method getTitle() does not exist on SilverStripe\ORM\Hierarchy\Hierarchy. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

547
        /** @scrutinizer ignore-call */ 
548
        $crumbs[] = $this->owner->getTitle();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
548
        return implode($separator, $crumbs);
549
    }
550
551
    /**
552
     * Flush all Hierarchy caches:
553
     * - Children (instance)
554
     * - NumChildren (instance)
555
     */
556
    public function flushCache()
557
    {
558
        $this->owner->_cache_children = null;
0 ignored issues
show
Bug Best Practice introduced by
The property _cache_children does not exist on SilverStripe\ORM\DataObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
Bug Best Practice introduced by
The property _cache_children does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
559
        self::$cache_numChildren = [];
560
    }
561
}
562