ILIAS  trunk Revision v11.0_alpha-3011-gc6b235a2e85
Node.php
Go to the documentation of this file.
1<?php
2
19declare(strict_types=1);
20
22
23class Node
24{
25 protected array $subnodes = [];
26 protected ?Node $container = null;
27 protected string $id;
28
29
30 protected int $current_points = 0;
31
32 public function __construct($id) //, array $subnodes = [])
33 {
34 $this->id = $id;
35 }
36
37 public function setSubnodes(array $subnodes)
38 {
39 if ($this->subnodes !== []) {
40 throw new \Exception("Use 'setSubnodes' during construction only", 1);
41 }
42 foreach ($subnodes as $subnode) {
43 $this->subnodes[$subnode->getId()] = $subnode->withContainer($this);
44 }
45 return $this;
46 }
47
51 public function withContainer(Node $node): self
52 {
53 $this->container = $node;
54 return $this;
55 }
56
57 protected function getContainer(): ?Node
58 {
59 return $this->container;
60 }
61
62 public function withSubnode($node)
63 {
64 $clone = clone $this;
65 $clone->subnodes[$node->getId()] = $node->withContainer($this);
66 return $clone;
67 }
68
69 public function getSubnodes(): array
70 {
71 return array_values($this->subnodes);
72 }
73
74 public function getSubnode(string $id): ?Node
75 {
76 return $this->subnodes[$id];
77 }
78
79 public function getPath(): array
80 {
81 $ret = [$this->getId()];
82 $node = $this;
83 while ($node = $node->getContainer()) {
84 $ret[] = $node->getId();
85 }
86 return array_reverse($ret);
87 }
88
89 public function findSubnodePath(string $id, ?Node $node = null): ?array
90 {
91 if (!$node) {
92 $node = $this;
93 }
94 if ($node->getId() == $id) {
95 return $node->getPath();
96 }
97 foreach ($node->getSubnodes() as $subnode) {
98 $result = $this->findSubnodePath($id, $subnode);
99 if ($result) {
100 return $result;
101 }
102 }
103
104 return null;
105 }
106
107 public function getId(): string
108 {
109 return $this->id;
110 }
111}
withContainer(Node $node)
this is only used internally - do not use apart from constructing the tree!
Definition: Node.php:51
findSubnodePath(string $id, ?Node $node=null)
Definition: Node.php:89
setSubnodes(array $subnodes)
Definition: Node.php:37