-
Notifications
You must be signed in to change notification settings - Fork 0
/
TemplateObject.php
722 lines (664 loc) · 18.6 KB
/
TemplateObject.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
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
<?php
/**
* Another simple template parser.
* Based on features of HTML_Template_IT by Ulf Wendel, Pierre-Alain Joye.
*
* @author Rebel
* @copyright (c) 2017 Aleksandr.ru
* @link https://github.com/Aleksandr-ru/TemplateObject Project page
* @link https://pear.php.net/package/HTML_Template_IT Original HTML_Template_IT
* @link http://aleksandr.ru Author's website
*
* @version 2.7
*/
class TemplateObject
{
/**
* Regexp to parse markup like
*
* ```
* <!-- EXTEND ../relative/path/to/file.html -->
* ```
*/
const REGEXP_EXTEND = '@^\s*<!--\s*EXTEND\s+(\S+)\s*-->@imU';
/**
* Regexp to parse markup like
*
* ```
* <!-- INCLUDE ../relative/path/to/file.html -->
* ```
*/
const REGEXP_INCLUDE = '@<!--\s*INCLUDE\s+(\S+)\s*-->@iU';
/**
* Regexp to parse markup like
*
* ```
* <!-- BEGIN block -->
* <a href="{{VAR}}">repeatable content</a>
* <!-- EMPTY block -->
* <img src="nothing.png" alt="In case of empty block" />
* <!-- END block -->
* ```
*/
const REGEXP_BLOCK = '@<!--\s*BEGIN\s+(?P<name>[a-z][a-z0-9_]*)(?P<options>(\s+[a-z0-9_]+)*)\s*-->(?P<data>.*)(<!--\s*EMPTY\s\g{name}\s*-->(?P<empty>.*))?<!--\s*END\s\g{name}\s*-->@ismU';
/**
* Regexp to parse markup like
*
* ```
* <!-- RECURSION blockname -->
* ```
*/
const REGEXP_RECURSION = '@<!--\s*RECURSION\s+(?P<name>[a-z][a-z0-9_]*)\s*-->@iU';
/**
* Regexp to parse markup like
*
* `{{VAR}}` `{{VAR|raw}}` `{{VAR|html}}` `{{VAR|js}}` `{{VAR|html|nl2br}}`
*/
const REGEXP_VAR = '@{{(?P<name>[a-z][a-z0-9_]*)(?P<filter>\|[a-z][a-z0-9\|]*)?}}@i';
/**
* Check value expression for addFilter function
* @see TemplateObject::addFilter() addFilter function
*/
const REGEXP_FILTER = '@^[a-z][a-z0-9]*$@';
/**
* Placeholder during parse time
*/
const PLACEHOLDER_BLOCK = '<!--__templateobjectblock[%s]__-->';
/**
* Placeholder during parse time
*/
const PLACEHOLDER_VAR = '<!--__templateobjectvariable[%s|%s]__-->';
/**
* Indicates that block with this option should be prepended to others in setBlock
* @see TemplateObject::setBlock() setBlock function
*/
const BLOCKOPTION_RSORT = 'rsort';
/**
* Debug mode to suppress user-level errors
* @var bool
*/
public $debug = false;
/**
* @var string $tmpl Template holder,
* @var string $out Output holder
*/
protected $tmpl, $out;
/**
* Original template holder for recursion
* @var string
*/
protected $template;
/**
* @var string[] $includes Array of included files,
* @var string $base_dir Base dir for includes
*/
protected $includes, $base_dir;
/**
* @var array $blocks Container for block markup,
* @see parseBlockCallback
*
* @var array $blockdata Container for block's data
* @see setBlock
*/
protected $blocks, $blockdata;
/**
* @var array $extended List of extended files,
* @var array $extend_blocks Container for block extenders
*/
protected $extended, $extend_blocks;
/**
* @var array $variables Container for variable markup
* @var array $vardata Container for variable's data
*/
protected $variables, $vardata;
/**
* Container for global variable's data
* @var array $vardata_global
*/
protected $vardata_global;
/**
* List of available filters
* @var array $filters array(filter => callback, ...)
*/
protected $filters = array(
'raw' => '', // do nothing
'html' => 'htmlspecialchars',
'nl2br' => 'nl2br',
'js' => 'addslashes',
);
/**
* Filters to be applied first if there is no "raw" filter is set
* stored in reversed order for performance
* @see applyVarFilter
* @var string[]
*/
protected $forced_filter = array('html');
/**
* Load template from file.
*
* @param string $file Path to template to be opened
*
* @return TemplateObject|FALSE A newly created object for given file or FALSE if empty
* @throws Exception
*/
static function loadTemplate($file)
{
$dir = dirname(realpath($file));
$filename = basename($file);
$data = file_get_contents($dir . DIRECTORY_SEPARATOR . $filename);
if(!$data) {
return FALSE;
}
else {
return new self($data, $dir);
}
}
/**
* Constructor.
*
* @param string $data In case of template from variable or DB
* @param string $base_dir Working directory for template
* @throws Exception
*/
function __construct($data = '', $base_dir = '')
{
$this->__destruct();
$this->template = $this->tmpl = $data;
$this->base_dir = $base_dir ? $base_dir : getcwd();
$this->parseExtend();
$this->parseIncludes();
$this->parseBlocks();
$this->parseRecursion();
$this->parseVariables();
}
/**
* Free and reset resources.
*/
function __destruct()
{
$this->template = '';
$this->tmpl = $this->out = '';
$this->includes = array();
$this->base_dir = '';
$this->blocks = $this->blockdata = array();
$this->variables = $this->vardata = array();
$this->vardata_global = array();
$this->extended = $this->extend_blocks = array();
}
/**
* Returns all blocks found in the template.
* Only 1st level of blocks are returned, not recursive.
*
* @return array List of found block names
*/
function getBlocks()
{
return array_keys($this->blocks);
}
/**
* Checks the existence of a block.
* Only 1st level of blocks are checked, not recursive.
*
* @param string $blockname name of the block
* @return bool whether block exists in template
*/
function hasBlock($blockname)
{
return array_key_exists($blockname, $this->blocks);
}
/**
* Returns all variables found in template.
* Only variables outside of blocks are returned.
*
* @return array List of found variable names
*/
function getVariables()
{
return array_keys($this->variables);
}
/**
* Checks the existence of a variable.
* Only variables outside of blocks are checked.
*
* @param string $varname name of the variable
* @return bool whether variable exists in template
*/
function hasVariable($varname)
{
return array_key_exists($varname, $this->variables);
}
/**
* Set block for usage (add a new block to markup and return handle).
*
* @param string $blockname Name of block in markup
*
* @return TemplateObject Block object
*/
function setBlock($blockname)
{
if(!isset($this->blocks[$blockname])) {
$this->debug and trigger_error("Unknown block '$blockname'", E_USER_NOTICE);
return FALSE;
}
$this->out = '';
$block = new self($this->blocks[$blockname]['data'], $this->base_dir);
$block->debug = $this->debug;
foreach($this->filters as $filter => $callback) $block->addFilter($filter, $callback, TRUE);
foreach($this->vardata_global as $var => $val) $block->setGlobalVariable($var, $val);
$block->setForcedFilter($this->getForcedFilter());
if(isset($this->blockdata[$blockname]) && in_array(self::BLOCKOPTION_RSORT, $this->blocks[$blockname]['options'])) {
array_unshift($this->blockdata[$blockname], $block);
return $this->blockdata[$blockname][0];
}
else {
return $this->blockdata[$blockname][] = $block;
}
}
/**
* Set a variable in global scope.
*
* @param string $var Name of the variable
* @param string $val Value of the variable
*
* @return bool Variable exists in the template
*/
function setGlobalVariable($var, $val)
{
$this->vardata_global[$var] = $val;
$this->out = '';
return isset($this->variables[$var]);
}
/**
* Set the variable in markup.
*
* Triggers E_USER_NOTICE if variable was not found.
*
* @param string $var Name of the variable
* @param string $val Value of the variable
*
* @return bool Whether variable was found
*/
function setVariable($var, $val)
{
if(!isset($this->variables[$var])) {
$this->debug and trigger_error("Unknown variable '$var'", E_USER_NOTICE);
return FALSE;
}
$this->vardata[$var] = $val;
$this->out = '';
return TRUE;
}
/**
* Set variables from an array like
*
* <pre>
* array(
* 'VAR1' => 'value',
* 'VAR2' => 'another value',
* 'singleblock' => array('BLOCKVAR1' => 'value1', 'BLOCKVAR2' => 'value2', ...),
* 'multiblock' => array(
* [0] => array('VAR1' => 'val1', 'VAR2' => 'val2'),
* [1] => array('VAR1' => 'val3', 'VAR2' => 'val4'),
* ),
* 'emptyblock' => NULL,
* ...)
* </pre>
*
* @param array $arr An array of variables and blocks data
*/
function setVarArray($arr)
{
foreach ($arr as $key => $value) {
if(is_array($value) && self::array_has_string_keys($value)) { // singleblock
$b = $this->setBlock($key) and $b->setVarArray($value);
}
elseif(is_array($value)) { // multiblock
foreach($value as $vv) if(is_array($vv) && self::array_has_string_keys($vv)) {
$b = $this->setBlock($key) and $b->setVarArray($vv);
}
else {
$this->debug and trigger_error("Incorrect variables array for block '$key'", E_USER_WARNING);
}
}
elseif(is_null($value)) { // emptyblock
$this->setBlock($key);
}
else {
$this->setVariable($key, $value);
}
}
}
/**
* Check whether the array has non-integer keys.
* @link http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
*
* @param array $array
*
* @return bool If the array has at leas one string key
*/
protected static function array_has_string_keys($array)
{
return count(array_filter(array_keys($array), 'is_string')) > 0;
}
/**
* Get parsed template with all data set.
*
* @return string
*/
function getOutput()
{
if($this->out) return $this->out;
$this->out = $this->tmpl;
//$empty = TRUE;
$vardata = array_merge($this->vardata_global, $this->vardata);
if($this->variables) foreach ($this->variables as $var => $vv) {
foreach($vv as $filter) {
$search = sprintf(self::PLACEHOLDER_VAR, $var, $filter);
if(isset($vardata[$var])) {
//$empty = FALSE;
$replace = $this->applyVarFilter($vardata[$var], $filter);
$this->out = str_replace($search, $replace, $this->out);
}
else {
$this->out = str_replace($search, '', $this->out);
}
}
}
if($this->blocks) foreach($this->blocks as $blockname => $block) {
$search = sprintf(self::PLACEHOLDER_BLOCK, $blockname);
$replace = '';
if(isset($this->blockdata[$blockname])) {
foreach ($this->blockdata[$blockname] as $b) {
$replace .= $b->getOutput();
}
//if($replace) $empty = FALSE;
}
if(!$replace && isset($block['empty'])) {
//$empty = FALSE;
$replace = $block['empty'];
}
$this->out = str_replace($search, $replace, $this->out);
}
return $this->out;
}
/**
* Print parsed template with all data set.
*/
function showOutput()
{
echo $this->getOutput();
}
/**
* Apply given var filter parameters to a value
*
* @param string $value
* @param string $filter
*
* @return string
*/
protected function applyVarFilter($value, $filter)
{
$filter = explode('|', $filter);
if (!in_array('raw', $filter)) {
foreach ($this->forced_filter as $ff) {
if (!in_array($ff, $filter)) {
array_unshift($filter, $ff);
}
}
}
while($f = array_shift($filter)) {
if(isset($this->filters[$f])) {
if(!$this->filters[$f]) {
// raw, do nothing
}
elseif(is_callable($this->filters[$f])) {
$value = call_user_func($this->filters[$f], $value);
}
else {
$this->debug and trigger_error("Filter function for '$f' is not callable!", E_USER_WARNING);
return FALSE;
}
}
else {
$this->debug and trigger_error("Unknown filter '$f'", E_USER_NOTICE);
return FALSE;
}
}
return $value;
}
/**
* Parse the EXTEND directive and convert template
*/
protected function parseExtend()
{
$matches = array();
while(preg_match(self::REGEXP_EXTEND, $this->tmpl, $matches)) {
$file = realpath($this->base_dir . DIRECTORY_SEPARATOR . $matches[1]);
if(in_array($file, $this->extended)) {
throw new Exception("Recursive extending of '$file'");
}
$this->extended[] = $file;
$matches = array();
preg_match_all(self::REGEXP_BLOCK, $this->tmpl, $matches, PREG_SET_ORDER);
while($m = array_shift($matches)) {
$this->extend_blocks[$m['name']] = $m['data'];
}
$this->tmpl = file_get_contents($file);
$this->base_dir = dirname($file);
$this->extendBlocks();
}
}
/**
* Parse markup and replace blocks with extenders
*/
protected function extendBlocks()
{
$this->tmpl = preg_replace_callback(self::REGEXP_BLOCK, array($this, 'extendBlocksCallback'), $this->tmpl);
}
/**
* Callback for extendBlocks function
* Replaces a block with its extender if present
*
* @param array $arr data from preg_replace_callback
*
* @return string
* @see extendBlocks()
*/
protected function extendBlocksCallback($arr)
{
if(isset($this->extend_blocks[$arr['name']])) {
return $this->extend_blocks[$arr['name']];
}
else {
return $arr[0];
}
}
/**
* Parse included templates recursievly and puts them to the main template
*/
protected function parseIncludes()
{
$count = 0;
$this->tmpl = preg_replace_callback(self::REGEXP_INCLUDE, array($this, 'parseIncludeCallback'), $this->tmpl, -1, $count);
if($count) {
$this->parseExtend();
$this->parseIncludes();
}
}
/**
* Callback for parseIncludes function
* Checks the included file for recursion and return its contents
*
* @param array $arr data from preg_replace_callback
*
* @return string
* @throws Exception
* @see parseIncludes()
*/
protected function parseIncludeCallback($arr)
{
$includefile = realpath($this->base_dir . DIRECTORY_SEPARATOR . $arr[1]);
if($includefile === FALSE) {
$this->debug and trigger_error("Failed to locate include '{$arr[1]}'", E_USER_NOTICE);
return '';
}
elseif(in_array($includefile, $this->includes)) {
throw new Exception("Recursive inclusion of '$includefile'");
}
$this->includes[] = $includefile;
return file_get_contents($includefile);
}
/**
* Parse block markup and replace blocks with placeholders
*/
protected function parseBlocks()
{
$this->tmpl = preg_replace_callback(self::REGEXP_BLOCK, array($this, 'parseBlockCallback'), $this->tmpl);
}
/**
* Callback for parseBlocks function
* Adds a block data and replaces markup with placeholder
*
* @param array $arr data from preg_replace_callback
*
* @return string
* @see parseBlocks()
*/
protected function parseBlockCallback($arr)
{
$this->blocks[$arr['name']] = array(
'data' => $arr['data'],
'empty' => isset($arr['empty']) ? $arr['empty'] : '',
'options' => preg_split("@\s+@", strtolower($arr['options']), -1, PREG_SPLIT_NO_EMPTY),
);
return sprintf(self::PLACEHOLDER_BLOCK, $arr['name']);
}
/**
* Parse recursion markup and replace it with block placeholdes
*/
protected function parseRecursion()
{
$this->tmpl = preg_replace_callback(self::REGEXP_RECURSION, array($this, 'parseRecursionCallback'), $this->tmpl);
}
/**
* Callback for parseRecursion function
* Adds a recursive block and replaces markup with placeholder
*
* @param array $arr data from preg_replace_callback
*
* @return string
* @see parseRecursion()
*/
protected function parseRecursionCallback($arr)
{
$this->blocks[$arr['name']] = array(
'data' => $this->template,
'empty' => '',
'options' => array(),
);
return sprintf(self::PLACEHOLDER_BLOCK, $arr['name']);
}
/**
* Parse variable markup and replace it with placeholders
*/
protected function parseVariables()
{
$this->tmpl = preg_replace_callback(self::REGEXP_VAR, array($this, 'parseVarCallback'), $this->tmpl);
}
/**
* Callback for parseVariables function
* Adds a variable data and replaces it with placeholder
*
* @param array $arr data from preg_replace_callback
*
* @return string
* @see parseVariables()
*/
protected function parseVarCallback($arr)
{
$filter = isset($arr['filter']) ? strtolower(trim($arr['filter'], '|')) : '';
if(!isset($this->variables[$arr['name']]) || !in_array($filter, $this->variables[$arr['name']])) {
$this->variables[$arr['name']][] = $filter;
}
return sprintf(self::PLACEHOLDER_VAR, $arr['name'], $filter);
}
/**
* Add (or replace) a filer for variables.
*
* Triggers E_USER_NOTICE if filter already exists and no $overwrite.
* Triggers E_USER_NOTICE when given $callback is not callable.
*
* @param string $filter Name of filter
* @param callable $callback A callback function
* @param bool $overwrite Whether to overwrite an existing filter
*
* @return bool Result of adding filter
*/
function addFilter($filter, $callback, $overwrite = FALSE)
{
if(!preg_match(self::REGEXP_FILTER, $filter)) {
$this->debug and trigger_error("Wrong filter '$filter'", E_USER_NOTICE);
return FALSE;
}
elseif(!$overwrite && isset($this->filters[$filter])) {
$this->debug and trigger_error("Filter '$filter' already exists, use overwrite to force", E_USER_NOTICE);
return FALSE;
}
if($callback && !is_callable($callback)) {
$this->debug and trigger_error("Callback is not callable for filter '$filter'", E_USER_NOTICE);
return FALSE;
}
$this->out = '';
$this->filters[$filter] = $callback;
return TRUE;
}
/**
* Remove an existing filter.
* Triggers E_USER_NOTICE if filter does not exist.
*
* @param string $filter Name of filter
*
* @return bool Result of removing filter
*/
function removeFilter($filter)
{
if(!isset($this->filters[$filter])) {
$this->debug and trigger_error("Filter '$filter' does not exist", E_USER_NOTICE);
return FALSE;
}
unset($this->filters[$filter]);
return TRUE;
}
/**
* Get current forced filter
*
* @return string filter
*/
function getForcedFilter()
{
$ff = array_reverse($this->forced_filter);
return implode('|', $ff);
}
/**
* Set new forced filter
*
* @param string $filter Can accept 'filter_one|filter_two'
*
* @return bool Result of changing value
*/
function setForcedFilter($filter)
{
$ff = explode('|', $filter);
$ff = array_filter(array_unique($ff));
if (!count($ff)) {
$this->debug and trigger_error("Filter '$filter' is empty", E_USER_WARNING);
return FALSE;
}
foreach ($ff as $f) if(!isset($this->filters[$f])) {
$this->debug and trigger_error("Filter '$f' does not exist", E_USER_WARNING);
return FALSE;
}
$this->forced_filter = array_reverse($ff);
return TRUE;
}
}