blob: 49c734967afcb931ca144a75b08d0c5a7bd115c1 [file] [log] [blame]
Matthias Andreas Benkardb382b102021-01-02 15:32:21 +01001<?php namespace Sieve;
2
3class SieveTree
4{
5 protected $childs_;
6 protected $parents_;
7 protected $nodes_;
8 protected $max_id_;
9 protected $dump_;
10
11 public function __construct($name = 'tree')
12 {
13 $this->childs_ = array();
14 $this->parents_ = array();
15 $this->nodes_ = array();
16 $this->max_id_ = 0;
17
18 $this->parents_[0] = null;
19 $this->nodes_[0] = $name;
20 }
21
22 public function addChild(SieveDumpable $child)
23 {
24 return $this->addChildTo($this->max_id_, $child);
25 }
26
27 public function addChildTo($parent_id, SieveDumpable $child)
28 {
29 if (!is_int($parent_id)
30 || !isset($this->nodes_[$parent_id]))
31 return null;
32
33 if (!isset($this->childs_[$parent_id]))
34 $this->childs_[$parent_id] = array();
35
36 $child_id = ++$this->max_id_;
37 $this->nodes_[$child_id] = $child;
38 $this->parents_[$child_id] = $parent_id;
39 array_push($this->childs_[$parent_id], $child_id);
40
41 return $child_id;
42 }
43
44 public function getRoot()
45 {
46 return 0;
47 }
48
49 public function getChilds($node_id)
50 {
51 if (!is_int($node_id)
52 || !isset($this->nodes_[$node_id]))
53 return null;
54
55 if (!isset($this->childs_[$node_id]))
56 return array();
57
58 return $this->childs_[$node_id];
59 }
60
61 public function getNode($node_id)
62 {
63 if ($node_id == 0 || !is_int($node_id)
64 || !isset($this->nodes_[$node_id]))
65 return null;
66
67 return $this->nodes_[$node_id];
68 }
69
70 public function dump()
71 {
72 $this->dump_ = $this->nodes_[$this->getRoot()] ."\n";
73 $this->dumpChilds_($this->getRoot(), ' ');
74 return $this->dump_;
75 }
76
77 protected function dumpChilds_($parent_id, $prefix)
78 {
79 if (!isset($this->childs_[$parent_id]))
80 return;
81
82 $childs = $this->childs_[$parent_id];
83 $last_child = count($childs);
84
85 for ($i=1; $i <= $last_child; ++$i)
86 {
87 $child_node = $this->nodes_[$childs[$i-1]];
88 $infix = ($i == $last_child ? '`--- ' : '|--- ');
89 $this->dump_ .= $prefix . $infix . $child_node->dump() . " (id:" . $childs[$i-1] . ")\n";
90
91 $next_prefix = $prefix . ($i == $last_child ? ' ' : '| ');
92 $this->dumpChilds_($childs[$i-1], $next_prefix);
93 }
94 }
95
96 public function getText()
97 {
98 $this->dump_ = '';
99 $this->childText_($this->getRoot());
100 return $this->dump_;
101 }
102
103 protected function childText_($parent_id)
104 {
105 if (!isset($this->childs_[$parent_id]))
106 return;
107
108 $childs = $this->childs_[$parent_id];
109
110 for ($i = 0; $i < count($childs); ++$i)
111 {
112 $child_node = $this->nodes_[$childs[$i]];
113 $this->dump_ .= $child_node->text();
114 $this->childText_($childs[$i]);
115 }
116 }
117}