Passed
Pull Request — 4 (#10077)
by
unknown
07:10
created

Hierarchy::getHierarchyBaseClass()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 5
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 9
rs 10
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\Core\ClassInfo;
8
use SilverStripe\Core\Extensible;
9
use SilverStripe\ORM\DataList;
10
use SilverStripe\ORM\SS_List;
11
use SilverStripe\ORM\ValidationResult;
12
use SilverStripe\ORM\ArrayList;
13
use SilverStripe\ORM\DataObject;
14
use SilverStripe\ORM\DataExtension;
15
use SilverStripe\ORM\DB;
16
use SilverStripe\Versioned\Versioned;
17
use SilverStripe\Core\Config\Config;
18
use SilverStripe\Core\Convert;
19
use Exception;
20
21
/**
22
 * DataObjects that use the Hierarchy extension can be be organised as a hierarchy, with children and parents. The most
23
 * obvious example of this is SiteTree.
24
 *
25
 * @property int $ParentID
26
 * @property DataObject|Hierarchy $owner
27
 * @method DataObject Parent()
28
 */
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;
0 ignored issues
show
introduced by
The private property $node_threshold_total is not used, and could be removed.
Loading history...
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;
0 ignored issues
show
introduced by
The private property $node_threshold_leaf is not used, and could be removed.
Loading history...
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;
0 ignored issues
show
introduced by
The private property $prepopulate_numchildren_cache is not used, and could be removed.
Loading history...
87
88
    /**
89
     * Prevent virtual page virtualising these fields
90
     *
91
     * @config
92
     * @var array
93
     */
94
    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...
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)
0 ignored issues
show
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

107
    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...
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

107
    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...
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) {
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...
125
            return;
126
        }
127
        // The object has no parent, won't be looping.
128
        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...
129
            return;
130
        }
131
        // The parent has not changed, skip the check for performance reasons.
132
        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

132
        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...
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();
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

153
            /** @scrutinizer ignore-call */ 
154
            $node = $node->Parent();
Loading history...
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();
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

181
        /** @scrutinizer ignore-call */ 
182
        $children = $node->AllChildren();
Loading history...
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;
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...
198
        if ($children) {
199
            return $children;
200
        }
201
202
        $children = $this
203
            ->owner
204
            ->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

204
            ->/** @scrutinizer ignore-call */ stageChildren(false)
Loading history...
205
            ->filterByCallback(function (DataObject $record) {
206
                return $record->canView();
207
            });
208
        $this->owner->_cache_children = $children;
0 ignored issues
show
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...
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...
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()) {
0 ignored issues
show
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

238
        if ($owner->hasExtension(Versioned::class) && $owner->/** @scrutinizer ignore-call */ hasStages()) {
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

238
        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 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

238
        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...
239
            // Next, go through the live children.  Only some of these will be listed
240
            $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

240
            /** @scrutinizer ignore-call */ 
241
            $liveChildren = $owner->liveChildren(true, true);
Loading history...
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);
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

248
        $owner->/** @scrutinizer ignore-call */ 
249
                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...
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();
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

268
        /** @scrutinizer ignore-call */ 
269
        $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...
269
        $parentIDColumn = $owner->getSchema()->sqlColumnForField($owner, 'ParentID');
0 ignored issues
show
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

269
        $parentIDColumn = $owner->getSchema()->sqlColumnForField(/** @scrutinizer ignore-type */ $owner, 'ParentID');
Loading history...
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

269
        $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...
270
        return Versioned::get_including_deleted(
271
            $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

271
            $owner->/** @scrutinizer ignore-call */ 
272
                    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...
272
            [ $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

272
            /** @scrutinizer ignore-type */ [ $parentIDColumn => $owner->ID ],
Loading history...
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;
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...
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()
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(), ["treeview", "listview", "getsubtree"]);
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;
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

440
        $hideFromHierarchy = $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...
441
        $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...
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);
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...
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')) {
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

467
        if (!$showAll && DataObject::getSchema()->fieldSpec(/** @scrutinizer ignore-type */ $this->owner, 'ShowInMenus')) {
Loading history...
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;
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...
492
        $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...
493
        $children = DataObject::get($this->getHierarchyBaseClass())
494
            ->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...
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')) {
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

506
        if (!$showAll && DataObject::getSchema()->fieldSpec(/** @scrutinizer ignore-type */ $owner, 'ShowInMenus')) {
Loading history...
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)
521
    {
522
        $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...
523
        if (empty($parentID)) {
524
            return null;
525
        }
526
        $baseClass = $this->owner->baseClass();
527
        $idSQL = $this->owner->getSchema()->sqlColumnForField($baseClass, 'ID');
528
        return DataObject::get_one($baseClass, [
529
            [$idSQL => $parentID],
530
            $filter
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()) {
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

548
        while ($object = $object->/** @scrutinizer ignore-call */ getParent()) {
Loading history...
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 = ' &raquo; ')
562
    {
563
        $crumbs = [];
564
        $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

564
        $ancestors = array_reverse($this->owner->/** @scrutinizer ignore-call */ getAncestors()->toArray());
Loading history...
565
        /** @var DataObject $ancestor */
566
        foreach ($ancestors as $ancestor) {
567
            $crumbs[] = $ancestor->getTitle();
568
        }
569
        $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

569
        /** @scrutinizer ignore-call */ 
570
        $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...
570
        return implode($separator, $crumbs);
571
    }
572
573
    /**
574
     * Flush all Hierarchy caches:
575
     * - Children (instance)
576
     * - NumChildren (instance)
577
     */
578
    public function flushCache()
579
    {
580
        $this->owner->_cache_children = null;
0 ignored issues
show
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...
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...
581
        self::$cache_numChildren = [];
582
    }
583
}
584