summaryrefslogtreecommitdiff
path: root/src/Concerns/HasAncestors.php
blob: 248e9c890b866567ec299c03c916d73bcf30fb5f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php

declare(strict_types=1);

namespace Lightscale\Router\Concerns;

trait HasAncestors
{
    private const MAX_ANCESTORY_DEPTH = 100;

    /** @return self[] */
    public function getAncestors(): array
    {
        $results = [];

        $count = 0;
        $instance = $this->parent;
        while (
            null !== $instance
            && $count++ < self::MAX_ANCESTORY_DEPTH
        ) {
            $results[] = $instance;
            $instance = $instance->parent;
        }

        return array_reverse($results);
    }

    /** @return self[] */
    public function getAncestorsAndSelf(): array
    {
        $results = $this->getAncestors();
        $results[] = $this;

        return $results;
    }
}