Don't return in FilterOutput() if there's a body already.
[hoplite.git] / views / template.php
1 <?php
2 // Hoplite
3 // Copyright (c) 2011 Blue Static
4 //
5 // This program is free software: you can redistribute it and/or modify it
6 // under the terms of the GNU General Public License as published by the Free
7 // Software Foundation, either version 3 of the License, or any later version.
8 //
9 // This program is distributed in the hope that it will be useful, but WITHOUT
10 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12 // more details.
13 //
14 // You should have received a copy of the GNU General Public License along with
15 // this program. If not, see <http://www.gnu.org/licenses/>.
16
17 namespace hoplite\views;
18
19 require_once HOPLITE_ROOT . '/base/filter.php';
20
21 /*!
22 A Template is initialized with a text file (typically HTML) and can render it
23 with data from some model. It has a short macro expansion system, equivalent
24 to PHP short open tags, but usable on all installations. Template caching of
25 the parsed state is available.
26 */
27 class Template
28 {
29 /*! @var string The name of the template. */
30 protected $template_name = '';
31
32 /*! @var string The compiled template. */
33 protected $data = NULL;
34
35 /*! @var array Variables to provide to the template. */
36 protected $vars = array();
37
38 /*!
39 Creates a new Template with a given name.
40 @param string
41 */
42 private function __construct($name)
43 {
44 $this->template_name = $name;
45 }
46
47 static public function NewWithData($data)
48 {
49 $template = new Template('');
50 $template->data = $template->_ProcessTemplate($data);
51 return $template;
52 }
53
54 static public function NewWithCompiledData($data)
55 {
56 $template = new Template('');
57 $template->data = $data;
58 return $template;
59 }
60
61 /*! Gets the name of the template. */
62 public function template_name() { return $this->template_name; }
63
64 /*! Gets the parsed data of the template. */
65 public function template() { return $this->data; }
66
67 /*! Overload property accessors to set view variables. */
68 public function __get($key)
69 {
70 return $this->vars[$key];
71 }
72 public function __set($key, $value)
73 {
74 $this->vars[$key] = $value;
75 }
76
77 /*! This includes the template and renders it out. */
78 public function Render()
79 {
80 $_template = $this->data;
81 $_vars = $this->vars;
82 $render = function () use ($_template, $_vars) {
83 extract($_vars);
84 eval('?>' . $_template . '<' . '?');
85 };
86
87 ob_start();
88 $render();
89 $data = ob_get_contents();
90 ob_end_clean();
91 return $data;
92 }
93
94 /*! @brief Does any pre-processing on the template.
95 This performs the macro expansion. The language is very simple and is merely
96 shorthand for the PHP tags.
97
98 The most common thing needed in templates is string escaped output from an
99 expression. HTML entities are automatically escaped in this format:
100 <p>Hello, {% $user->name %}!</p>
101
102 To specify the type to format, you use the pipe symbol and then one of the
103 following types: str (default; above), int, float, raw.
104 <p>Hello, {% %user->name | str %}</p>
105 <p>Hello, user #{% $user->user_id | int %}</p>
106
107 To evaluate a non-printing expression, simply add a '!' before the first '%':
108 {!% if (!$user->user_id): %}<p>Hello, Guest!</p>{!% endif %}
109
110 @param string Raw template data
111 @return string Executable PHP
112 */
113 protected function _ProcessTemplate($data)
114 {
115 // The parsed output as compiled PHP.
116 $processed = '';
117
118 // If processing a macro, this contains the contents of the macro while
119 // it is being extracted from the template.
120 $macro = '';
121 $in_macro = FALSE;
122
123 $length = strlen($data);
124 $i = 0; // The current position of the iterator.
125 $looking_for_end = FALSE; // Whehter or not an end tag is expected.
126 $line_number = 1; // The current line number.
127 $i_last_line = 0; // The value of |i| at the previous new line, used for column numbering.
128
129 while ($i < $length) {
130 // See how far the current position is from the end of the string.
131 $delta = $length - $i;
132
133 // When a new line is reached, update the counters.
134 if ($data[$i] == "\n") {
135 ++$line_number;
136 $i_last_line = $i;
137 }
138
139 // Check for simple PHP short-tag expansion.
140 if ($delta >= 3 && substr($data, $i, 3) == '{!%') {
141 // If an expansion has already been opened, then it's an error to nest.
142 if ($looking_for_end) {
143 $column = $i - $i_last_line;
144 throw new TemplateException("Unexpected start of expansion at line $line_number:$column");
145 }
146
147 $looking_for_end = TRUE;
148 $processed .= '<' . '?php';
149 $i += 3;
150 continue;
151 }
152 // Check for either the end tag or the start of a macro expansion.
153 else if ($delta >= 2) {
154 $substr = substr($data, $i, 2);
155 // Check for an end tag.
156 if ($substr == '%}') {
157 // If an end tag was encountered without an open tag, that's an error.
158 if (!$looking_for_end) {
159 $column = $i - $i_last_line;
160 throw new TemplateException("Unexpected end of expansion at line $line_number:$column");
161 }
162
163 // If this is a macro, it's time to process it.
164 if ($in_macro)
165 $processed .= $this->_ProcessMacro($macro);
166
167 $looking_for_end = FALSE;
168 $in_macro = FALSE;
169 $processed .= ' ?>';
170 $i += 2;
171 continue;
172 }
173 // Check for the beginning of a macro.
174 else if ($substr == '{%') {
175 // If an expansion has already been opened, then it's an error to nest.
176 if ($looking_for_end) {
177 $column = $i - $i_last_line;
178 throw new TemplateException("Unexpected start of expansion at line $line_number:$column");
179 }
180
181 $processed .= '<' . '?php echo ';
182 $macro = '';
183 $in_macro = TRUE;
184 $looking_for_end = TRUE;
185 $i += 2;
186 continue;
187 }
188 }
189
190 // All other characters go into a storage bin. If currently in a macro,
191 // save off the data separately for parsing.
192 if ($in_macro)
193 $macro .= $data[$i];
194 else
195 $processed .= $data[$i];
196 ++$i;
197 }
198
199 return $processed;
200 }
201
202 /*!
203 Takes the contents of a macro |{% $some_var | int %}|, which is the part in
204 between the open and close brackets (excluding '%') and transforms it into a
205 PHP statement.
206 */
207 protected function _ProcessMacro($macro)
208 {
209 // The pipe operator specifies how to sanitize the output.
210 $formatter_pos = strrpos($macro, '|');
211
212 // No specifier defaults to escaped string.
213 if ($formatter_pos === FALSE)
214 return 'hoplite\\base\\filter\\String(' . $macro . ')';
215
216 // Otherwise, apply the right filter.
217 $formatter = trim(substr($macro, $formatter_pos + 1));
218 $function = '';
219 switch (strtolower($formatter)) {
220 case 'int': $function = 'Int'; break;
221 case 'float': $function = 'Float'; break;
222 case 'str': $function = 'String'; break;
223 case 'raw': $function = 'RawString'; break;
224 default:
225 throw new TemplateException('Invalid macro formatter "' . $formatter . '"');
226 }
227
228 // Now get the expression and return a PHP statement.
229 $expression = trim(substr($macro, 0, $formatter_pos));
230 return 'hoplite\\base\\filter\\' . $function . '(' . $expression . ')';
231 }
232 }
233
234 class TemplateException extends \Exception {}