-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclass.template.php
More file actions
545 lines (469 loc) · 14.3 KB
/
Copy pathclass.template.php
File metadata and controls
545 lines (469 loc) · 14.3 KB
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
<?php
namespace Sleepy;
/**
* Provides templating functionality by replacing placeholder with content.
*
* ## Usage
*
* Templates are defined in .tpl files and live in *\/app\/templates*. Templates consist of HTML and
* *placeholders* that are defined by double curly braces, e.g. {{ page_title }}
*
* ### Template file: *\app\templates\default.tpl*
* ~~~ php
* <html>
* <head>
* <title>{{ page_title }}</title>
* </head>
* <body>
* <h1>{{ heading }}</h1>
* <p>This page has been viewed {{ hits }} times.</p>
* </body>
* </html>
* ~~~
*
* Templates are used by instantiating the Template class and passing the template URL to the
* constructor. The bind method is used to map the placeholders to content.
*
* ### PHP file: *index.php*
*
* ~~~ php
* require_once('include/sleepy.php');
* $page = new \Sleepy\Template('templates/default.tpl');
* $page->bind('page_title', 'Sleepy Mustache');
* $page->bind('heading', 'Hello world!');
* $page->show(); // Display the compiled template
* ~~~
*
* #### Components
*
* Components are design to be reusable templates. They can be attached to other templates by using
* the *#include* directive. Good examples are *header.tpl* or *slideshow.tpl*.
*
* ### PHP file: *\app\templates\components\header.tpl*
*
* ~~~ php
* <html>
* <head>
* <title>{{ page_title }}</title>
* </head>
* <body>
* ~~~
*
* ### PHP file: *\app\templates\components\footer.tpl*
*
* ~~~ php
* </body>
* </html>
* ~~~
*
* ### Template file: *\app\templates\default.tpl*
* ~~~ php
* {{#include components/header.tpl }}
* <h1>{{ heading }}</h1>
* <p>This page has been viewed {{ hits }} times.</p>
* {{#include components/footer.tpl }}
* ~~~
*
* ### Binding Arrays
*
* Many times you need to bind an array of data to a template. For example, a slideshow or list of
* users. In this case, we use the #each directives to loop thru the array.
*
* ### Template file: *\app\templates\users.tpl*
*
* ~~~ php
* {#each u in users}
* <div>
* <h3>{{ u.name }}</h3>
* <p>{{ u.description }}</p>
* </div>
* {\each}
* ~~~
*
* ## Changelog
*
* ### Version 1.10.1
* * Updated documentation
*
* ### Version 1.10
* * Add rudimentary if statement blocks
*
* ### Version 1.9
* * Add Action for individual Template Starts per $template name
*
* ### Version 1.8
* * Allow Template::bind() to take an array to bind multiple values at once
*
* ### Version 1.7
* * Updated private prefix (_) for consistency
* * Updated documentation
*
* ### Version 1.6
* * No longer dependant on Hooks Module
*
* @date February 13, 2020
* @author Jaime A. Rodriguez <hi.i.am.jaime@gmail.com>
* @version 1.10.1
* @license http://opensource.org/licenses/MIT
*/
class Template {
/**
* The extension for template files
*
* @var string
*/
public $extension = '.tpl';
/**
* The template directory
*
* @var string
*/
public $directory;
/**
* The template file
*
* @var string
*/
protected $_file;
/**
* The data bound to the template
*
* @var mixed[]
*/
protected $_data = array();
/**
* The constructor
*
* @param string $template The name of the template
* @param string $basedir The base directory for template files
* @return void
*/
public function __construct($template='', $basedir='') {
if (class_exists('\Sleepy\Hook')) {
Hook::addAction('template_start');
Hook::addAction('template_start' . $template);
}
// If they didn't pass a basedir then try the default
if ($basedir == '') {
if (!defined('DIRBASE')) {
define('DIRBASE', $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'app');
}
$this->directory = DIRBASE . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR;
} else {
$this->directory = $basedir;
}
if (!empty($template)) {
$this->setTemplate($template);
}
}
/**
* Does the template exist?
*
* @param string $file Name of template
* @return bool True if template exists
*/
private function _checkTemplate($file) {
if (empty($file)) {
throw new \Exception('Template file has not been set.');
}
// Check that the directory is set correctly
if (!file_exists($this->directory)) {
throw new \Exception("Template directory '{$this->directory}' does not exists.");
}
// Check if the template exists in the directory
if (!file_exists($this->directory . $file . $this->extension)) {
throw new \Exception("Template '{$this->directory}{$file}{$this->extension}' does not exist.");
}
return true;
}
/**
* Given a path, the function returns a piece of $arr. For example
* 'name.first' will return $arr['name']['first']
*
* @param array $arr An array to search using the $path
* @param string $path A path representing the dimensions of the array
* @return mixed A sub-array or string
*/
private function _assignArrayByPath($arr, $path) {
$keys = explode('.', $path);
if (is_array($keys)) {
foreach ($keys as $key) {
if (array_key_exists($key, $arr)) {
$arr = $arr[$key];
} else {
return false;
}
}
}
return $arr;
}
/**
* Renders the template
*
* @param string $template The template to render
* @param mixed[] $data The data bound to the template
* @return string The rendered template
*/
private function _render($template, $data) {
$template = $this->_renderInclude($template);
$template = $this->_renderEach($template, $data);
$template = $this->_renderIf($template, $data);
if (class_exists('\Sleepy\Hook')) {
$template = Hook::addFilter('prerender_template', $template);
}
$template = $this->_renderPlaceholder($template, $data);
return $template;
}
/**
* Render the if blocks
*
* @todo Not very robust, remove eval at a later date
* @todo Add Else blcok
* @todo Add tests
*
* @param string $template
* @param mixed[] $data
* @return void
*/
private function _renderIf($template, $data) {
// Process the #if blocks
if (preg_match_all('/{{\s?#if.+?}}(?:(?>[^{}]+)|(?R))*{{\s?\/if\s?}}/ism', $template, $ifs)) {
// For every #if
foreach ($ifs[0] as $value) {
// Reset rendered data
$rendered = '';
// break statement into 3 pieces (val1) (operator) (val2)
preg_match('/{{\s?#if\s?(?<val1>.*?)\s(?<oper>.*?)\s(?<val2>.*?)\s?}}/', $value, $tokens);
// Replace placeholders
if (isset($this->_data[$tokens[1]])) {
$tokens[1] = &$this->_data[$tokens[1]];
} else {
$tokens[1] = trim(trim($tokens[1], '"'), "'");
}
// Replace placeholders
if (isset($this->_data[$tokens[3]])) {
$tokens[3] = &$this->_data[$tokens[3]];
} else {
$tokens[3] = trim(trim($tokens[3], '"'), "'");
}
// Evaluate if Statement
$truthy = eval("return \$tokens[1] $tokens[2] \$tokens[3];");
if ($truthy) {
// replace with the if statements
$new_template = preg_replace('/{{\s?#if.*?}}/s', '', $value, 1);
$new_template = preg_replace('/{{\s?\/if\s?}}$/s', '', $new_template, 1);
} else {
$new_template = str_replace($value, '', $value);
}
$rendered = $rendered . $this->_render($new_template, $data);
$template = str_replace($value, $rendered, $template);
}
}
return $template;
}
/**
* Render the includes
*
* @param string $template
* @return void
*/
private function _renderInclude($template) {
// Process the includes
if (preg_match('/{{\s*#include\s.*}}/', $template, $include)) {
$index = trim(str_replace('{{', '', str_replace('}}', '', $include[0])));
if (file_exists($this->directory . str_replace('#include ', '', $index) . $this->extension)) {
ob_start();
include($this->directory . str_replace('#include ', '', $index) . $this->extension);
} else {
ob_clean(); // clear buffer in $this->show();
throw new \Exception($this->directory . str_replace('#include ', '', $index) . $this->extension . ' doesn\'t exist. Cannot include file.');
}
$template = $this->_renderInclude(str_replace($include[0], ob_get_clean(), $template));
}
return $template;
}
/**
* Render the each blocks
*
* @param string $template
* @param mixed[] $data
* @return void
*/
private function _renderEach($template, $data) {
// Process the #each blocks
if (preg_match_all('/{{\s?#each.+?}}(?:(?>[^{}]+)|(?R))*{{\s?\/each\s?}}/ism', $template, $loops)) {
// For every #each
foreach ($loops[0] as $value) {
// Reset rendered data
$rendered = '';
// Stores the values of <for> and <in> into $forin
preg_match('/{{\s?#each\s(?<for>\w+) in (?<in>.*?)\s?}}/', $value, $forin);
$forin['in'] = strtolower($forin['in']);
// Removes the each loop
$new_template = preg_replace('/{{\s?#each.*?}}/s', '', $value, 1);
$new_template = preg_replace('/{{\s?\/each\s?}}$/s', '', $new_template, 1);
// get the array based on the <in>
$in = $this->_assignArrayByPath($data, $forin['in']);
// for each changelog
if (is_array($in[0])) {
// Allow hooks to edit the data
if (class_exists('\Sleepy\Hook')) {
$in = Hook::addFilter('template_each_array', array($in));
}
$iterator = 0;
foreach ($in as $new_data) {
$iterator++;
if (class_exists('\Sleepy\Hook')) {
$new_data = Hook::addFilter('template_each', array($new_data));
$new_data = Hook::addFilter('template_each_' . $forin['for'], array($new_data));
}
$new_data['iterator'] = $iterator;
$new_data['zebra'] = ($iterator % 2) ? 'odd' : 'even';
// Make the $new_data match the <for>
$new_data[$forin['for']] = $new_data;
// render the new template
$rendered = $rendered . $this->_render($new_template, $new_data);
}
} else {
// render the new template
$rendered = $rendered . $this->_render($new_template, $data);
}
$template = str_replace($value, $rendered, $template);
}
}
return $template;
}
/**
* Render the placeholders
*
* @param string $template
* @param mixed[] $data
* @return void
*/
private function _renderPlaceholder($template, $data) {
// Find all the single placeholders
preg_match_all('/{{\s?(.*?)(\s.*?)?\s?}}/', $template, $matches);
// For each replace with a value
foreach (array_unique($matches[0]) as $index => $placeholder) {
$key = strtolower($matches[1][$index]);
$arguments = array(
$this->_assignArrayByPath($data, $key)
);
# We trim so that there are no extra blank arguments
$arguments = array_merge($arguments, explode(' ', trim($matches[2][$index])));
$boundData = $arguments;
if (class_exists('\Sleepy\Hook')) {
$boundData = Hook::addFilter('render_placeholder_' . strtolower($key), $boundData);
}
// Some filters might take arrays and return only a single value, if
// hooks are disabled, lets return only this single value
if (is_array($boundData)) {
$boundData = $boundData[0];
}
$template = str_replace($placeholder, $boundData, $template);
}
return $template;
}
/**
* Parses the template after it's been setup
*
* @return string The rendered template
*/
private function _parseTemplate() {
$this->_checkTemplate($this->_file);
// Render template file
ob_start();
include($this->directory . $this->_file . $this->extension);
$template = $this->_render(ob_get_clean(), $this->_data);
if (class_exists('\Sleepy\Hook')) {
$template = Hook::addFilter('render_template_' . $this->_file, $template);
$template = Hook::addFilter('render_template', $template);
}
return $template;
}
/**
* Sets the template to use.
*
* @param string $file The Filename
* @return void
*/
public function setTemplate($file) {
if ($this->_checkTemplate($file)) {
$this->_file = $file;
}
}
/**
* Binds data to the template placeholders
*
* @param mixed $placeholder The template placeholder
* @param mixed $value The value that replaced the placeholder
* @return void
*/
public function bind($placeholder, $value='') {
if (!is_array($placeholder)) {
$placeholder = array(
trim(strtolower($placeholder)) => $value
);
}
foreach($placeholder as $key => $value) {
$key = trim(strtolower($key));
if (!is_array($value)) {
if (class_exists('\Sleepy\Hook')) {
$value = Hook::addFilter('bind_placeholder_' . trim($key), $value);
}
}
$this->_data[$key] = $value;
}
}
/**
* Starts a buffer that will bind data to the template placeholders. The
* buffer will capture anything you output until $this->bindStop()
*
* @return void
*/
public function bindStart() {
ob_start();
}
/**
* Stops the buffer that binds data to the template placeholders
*
* @param string $placeholder The template placeholder
* @return void
*/
public function bindStop($placeholder) {
$content = ob_get_clean();
if (class_exists('\Sleepy\Hook')) {
$content = Hook::addFilter('bind_placeholder_' . $placeholder, $content);
}
$this->_data[trim(strtolower($placeholder))] = $content;
}
/**
* Gets the data for a placeholder
*
* @param string $placeholder The placeholder
* @return mixed The data stored in the placeholder
*/
public function get($key) {
$value = $this->_data[$key];
if (class_exists('\Sleepy\Hook')) {
Hook::addFilter('template_get_' . $key, $value);
}
return $value;
}
/**
* Shows the rendered template
*
* @return void
*/
public function show() {
echo $this->_parseTemplate();
}
/**
* Retrieves the rendered template
*
* @return void
*/
public function retrieve() {
return $this->_parseTemplate();
}
}