forked from jasonmoo/t.js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
t.php
123 lines (98 loc) · 3.54 KB
/
t.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
<?php
class T {
private $blockregex = '/\\{\\{(([@!]?)(.+?))\\}\\}(([\\s\\S]+?)(\\{\\{:\\1\\}\\}([\\s\\S]+?))?)\\{\\{\\/\\1\\}\\}/';
private $valregex = '/\\{\\{([=%])(.+?)\\}\\}/';
private $vars = false;
private $key = false;
private $t = '';
private $result = '';
public function __construct($template){
$this->t = $template;
}
public function scrub($val){
//useful to parse messages, emoji etc
return htmlspecialchars($val.'', ENT_QUOTES);
}
public function get_value($index) {
$index = explode('.', $index);
return $this->search_value($index, $this->vars);
}
private function search_value($index, $value) {
if(is_array($index) and
count($index)) {
$current_index = array_shift($index);
}
if(is_array($index) and
count($index) and
is_array($value[$current_index]) and
count($value[$current_index])) {
return $this->search_value($index, $value[$current_index]);
} else {
$val = isset($value[$current_index])?$value[$current_index]:'';
return str_replace('{{', "{\f{", $val);
}
}
public function matchTags($matches) {
$_ = $matches[0];
$__ = $matches[1];
$meta = $matches[2];
$key = $matches[3];
$inner = $matches[4];
$if_true = $matches[5];
$has_else = $matches[6];
$if_false = $matches[7];
$val = $this->get_value($key);
$temp = "";
$i;
if (!$val) {
// handle if not
if ($meta == '!') {
return $this->render($inner);
}
// check for else
if ($has_else) {
return $this->render($if_false);
}
return "";
}
// regular if
if (!$meta) {
return $this->render($if_true);
}
// process array/obj iteration
if ($meta == '@') {
// store any previous vars
// reuse existing vars
$_ = $this->vars['_key'];
$__ = $this->vars['_val'];
foreach ($val as $i => $v) {
$this->vars['_key'] = $i;
$this->vars['_val'] = $v;
$temp .= $this->render($inner);
}
$this->vars['_key'] = $_;
$this->vars['_val'] = $__;
return $temp;
}
}
public function replaceTags($matches) {
$_ = $matches[0];
$meta = $matches[1];
$key = $matches[2];
$val = $this->get_value($key);
if ($val || $val === 0) {
return $meta == '%' ? $this->scrub($val) : $val;
}
return "";
}
private function render($fragment) {
$matchTags = preg_replace_callback($this->blockregex, array($this, "matchTags"), $fragment);
$replaceTags = preg_replace_callback($this->valregex, array($this, "replaceTags"), $matchTags);
return $replaceTags;
}
public function parse($obj){
$this->vars = $obj;
return $this->render($this->t);
}
}
?>