summaryrefslogtreecommitdiff
path: root/src/PathSegment.php
blob: 7f24660fab68736c006e2ada762d19cf9e73eda8 (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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php

declare(strict_types=1);

namespace Lightscale\Router;

use Lightscale\Router\Enums\HttpMethod;
use Lightscale\Router\Enums\SpecialSegment;

class PathSegment
{
    private const MAX_ANCESTORY_DEPTH = 100;

    protected string $content;

    protected ?SpecialSegment $specialSegment = null;

    /** @var array<string, self> */
    protected array $children;

    /** @var array<value-of<HttpMethod>, Route[]> */
    protected array $routes = [];

    public function __construct(
        SpecialSegment|string $content,
        protected ?self $parent = null,
    ) {
        if ($content instanceof SpecialSegment) {
            $this->content = $content->value;
            $this->specialSegment = $content;
        } else {
            $this->content = $content;
        }
    }

    public function getContent(): string
    {
        return $this->content;
    }

    public function getParent(): ?self
    {
        return $this->parent;
    }

    /** @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;
    }

    public function addChild(self $segment): void
    {
        $this->children[$segment->getContent()] = $segment;
    }

    /** @return array<string, self> */
    public function getChildren(): array
    {
        return $this->children;
    }

    public function addRoute(): void
    {
    }
}