-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathIndexTable.php
101 lines (80 loc) · 2.42 KB
/
IndexTable.php
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
//TODO Dynamic length of levels, not limited to 5!
if (!defined('INC_PATH')) {
define ('INC_PATH', realpath(dirname(__FILE__).'/../../').'/');
}
require_once INC_PATH.'pwTools/string/StringTools.php';
require_once INC_PATH.'pwTools/data/IndexItem.php';
class IndexTable {
private $_cont;
private $_lastlevel;
private $_levels;
private static $MAXLEVEL = 6;
public function __construct() {
$this->_cont = array();
$this->_levels = array_fill(1, self::$MAXLEVEL, 0);
$this->_lastlevel = 0;
}
public function add($level, $text) {
if(!is_int($level) || $level > self::$MAXLEVEL || $level < 1) {
throw new Exception("IndexTable: add: Invalid level '$level'. MAXLEVEL=".self::$MAXLEVEL);
}
if ($this->_lastlevel > $level) {
for($i = $level+1; $i <= self::$MAXLEVEL; $i++) {
$this->_levels[$i] = 0;
}
}
$this->_levels[$level]++;
$l = $this->_levels;
$id = StringTools::rightTrim("$l[1].$l[2].$l[3].$l[4].$l[5]", ".0");
$item = new IndexItem($id, $level, $text);
$this->_lastlevel = $level;
$this->_cont[] = $item;
}
public function __toString() {
$out = "";
foreach($this->_cont as $item) {
$out .= $item."\n";
}
return $out;
}
public function getAsArray() {
return $this->_cont;
}
public function getByIndex($index) {
if($index >= sizeof($this->_cont)) {
throw new Exception("Index out of bounds!");
}
return $this->_cont[$index];
}
public function getByIdOrText($idOrText) {
$idOrText = self::normalizeText($idOrText);
foreach ($this->_cont as $item) {
if (self::normalizeText($item->getText()) == $idOrText || $item->getId() == $idOrText) {
return $item;
}
}
throw new Exception("Id or text '$idOrText' not found in this index table.");
}
public function getById($id) {
foreach ($this->_cont as $item) {
if ($item->getId() == $id) {
return $item;
}
}
throw new Exception("Id '$id' not found in this index table.");
}
public function getByText($text) {
$text = self::normalizeText($text);
foreach ($this->_cont as $item) {
if (self::normalizeText($item->getText()) == $text) {
return $item;
}
}
throw new Exception("Text '$text' not found in this index table.");
}
private static function normalizeText($text) {
return pw_s2e(utf8_strtolower(utf8_trim(pw_s2u($text))));
}
}
?>