-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTemplate.php
1231 lines (1037 loc) · 41.8 KB
/
Template.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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Template Class
*
* @category Template
* @package Template
* @author Osman Cakmak <[email protected]>
* @copyright Copyright (c) 2024-?
* @license http://opensource.org/licenses/gpl-3.0.html GNU Public License
* @link https://github.com/oxcakmak/PHP-Template-Class
* @version 1.1.5
*/
class Template {
/** @var array Variables available to templates */
private $variables = [];
/** @var string Directory containing template files */
private $templateDir;
/** @var string File extension for template files */
private $templateExt;
/** @var int Maximum memory usage allowed (256MB default) */
private $maxMemory = 268435456;
/** @var int Maximum iterations for recursive template processing */
private $maxIterations = 10;
/** @var string Error handling mode: 'comment', 'exception', or 'silent' */
private $errorMode = 'comment';
/** @var bool Enable debug mode for detailed error messages */
private $debugMode = false;
/**
* Constructor
*
* @param string $templateDir Directory containing template files
* @param string $templateExt File extension for template files (default: html)
* @param array $options Additional options for template engine
* @throws Exception If template directory is not specified or does not exist
*/
public function __construct($templateDir, $templateExt = 'html', $options = []) {
if (empty($templateDir)) {
throw new Exception("Template directory must be specified");
}
// Ensure template directory ends with a directory separator
if (substr($templateDir, -1) !== DIRECTORY_SEPARATOR) {
$templateDir .= DIRECTORY_SEPARATOR;
}
// Check if template directory exists
if (!is_dir($templateDir)) {
throw new Exception("Template directory does not exist: {$templateDir}");
}
$this->templateDir = $templateDir;
$this->templateExt = $templateExt;
// Set options if provided
if (isset($options['maxMemory'])) {
$this->maxMemory = (int)$options['maxMemory'];
}
if (isset($options['maxIterations'])) {
$this->maxIterations = (int)$options['maxIterations'];
}
if (isset($options['errorMode']) && in_array($options['errorMode'], ['comment', 'exception', 'silent'])) {
$this->errorMode = $options['errorMode'];
}
if (isset($options['debugMode'])) {
$this->debugMode = (bool)$options['debugMode'];
}
}
/**
* Assign a variable to the template
*
* @param string $name Variable name
* @param mixed $value Variable value
* @return Template For method chaining
*/
public function assign($name, $value) {
$this->variables[$name] = $value;
return $this;
}
/**
* Assign multiple variables to the template
*
* @param array $variables Associative array of variables
* @return Template For method chaining
*/
public function assignMultiple($variables) {
if (is_array($variables)) {
foreach ($variables as $name => $value) {
$this->variables[$name] = $value;
}
}
return $this;
}
/**
* Load and process a template file
*
* @param string $templateName Name of the template file (without extension)
* @return string Processed template content
* @throws Exception If template file does not exist
*/
public function load($templateName) {
$templatePath = $this->templateDir . $templateName . '.' . $this->templateExt;
if (!file_exists($templatePath)) {
throw new Exception("Template file not found: {$templatePath}");
}
$content = file_get_contents($templatePath);
return $this->processTemplate($content);
}
/**
* Process template content
*
* @param string $template Template content to process
* @return string Processed template content
*/
private function processTemplate($template) {
$iteration = 0;
$lastTemplate = '';
while ($template !== $lastTemplate && $iteration < $this->maxIterations) {
$this->checkMemoryUsage();
$lastTemplate = $template;
// Process includes first
$template = preg_replace_callback(
'/\{\{\s*inc\(([^)]+)\)\s*\}\}/',
array($this, 'processFunction'),
$template
);
// Process function calls with parameters - FIX HERE
$template = preg_replace_callback(
'/\{\{\s*([a-zA-Z0-9_]+)\s*\(\s*(.*?)\s*\)\s*\}\}/s',
array($this, 'processFunctionCall'),
$template
);
// Process for loops
$template = $this->processForLoops($template);
// Process if conditions
$template = $this->processIfConditions($template);
// Process variables
$template = $this->processVariablesInContent($template);
$iteration++;
}
return $this->cleanupTemplate($template);
}
/**
* Process for loops in templates
*
* @param string $template The template content
* @return string The processed template
*/
private function processForLoops($template) {
// Process key-value for loops first
$template = preg_replace_callback(
'/\{%\s*for\s+([a-zA-Z0-9_]+)\s*,\s*([a-zA-Z0-9_]+)\s+in\s+([a-zA-Z0-9._\[\]\'"]+)\s*%\}([\s\S]*?)\{%\s*endfor\s*%\}/s',
array($this, 'processKeyValueForLoop'),
$template
);
// Then process regular for loops
$template = preg_replace_callback(
'/\{%\s*for\s+([a-zA-Z0-9_]+)\s+in\s+([a-zA-Z0-9._\[\]\'"]+)\s*%\}([\s\S]*?)\{%\s*endfor\s*%\}/s',
array($this, 'processForLoop'),
$template
);
return $template;
}
/**
* Process a regular for loop
*
* @param array $matches Regex matches from preg_replace_callback
* @return string The processed loop content
*/
private function processForLoop($matches) {
$itemName = $matches[1];
$arrayPath = $matches[2];
$content = $matches[3];
// Get the array to iterate over
$array = $this->getNestedValue($arrayPath);
// If not an array or empty, return appropriate message
if (!is_array($array)) {
if ($this->debugMode) {
return "<!-- Debug: Array '{$arrayPath}' not found or not an array -->";
}
return '';
}
$result = '';
// Store original variables to restore later
$originalVars = $this->variables;
$arrayLength = count($array);
$index = 0;
// Store original loop variable if it exists (for nested loops)
$originalLoop = isset($this->variables['loop']) ? $this->variables['loop'] : null;
foreach ($array as $key => $item) {
$this->checkMemoryUsage();
// Create a NEW COPY of the variables for this iteration
// This is crucial for nested loops to work correctly
$iterationVars = $originalVars;
// Set the item variable in the current scope
$iterationVars[$itemName] = $item;
// Add loop metadata
$iterationVars['loop'] = [
'index' => $index + 1,
'index0' => $index,
'first' => ($index === 0),
'last' => ($index === $arrayLength - 1),
'length' => $arrayLength,
'parent' => $originalLoop
];
// Set the variables for this iteration
$this->variables = $iterationVars;
// Process the content for this iteration
$iterationContent = $content;
// Process nested loops first
$iterationContent = $this->processForLoops($iterationContent);
// Process if conditions after nested loops
$iterationContent = $this->processIfConditions($iterationContent);
// Process variables last
$iterationContent = $this->processVariablesInContent($iterationContent);
$result .= $iterationContent;
$index++;
}
// Restore original variables
$this->variables = $originalVars;
return $result;
}
/**
* Helper method to get a property from an array using a dot notation path
*
* @param array $array The array to get the property from
* @param string $path The path to the property (dot notation)
* @return mixed The property value or null if not found
*/
private function getPropertyFromArray($array, $path) {
$parts = explode('.', $path);
$current = $array;
foreach ($parts as $part) {
if (empty($part)) continue;
if (is_array($current) && array_key_exists($part, $current)) {
$current = $current[$part];
} else {
return null;
}
}
return $current;
}
/**
* Process a key-value for loop
*
* @param array $matches Regex matches from preg_replace_callback
* @return string The processed loop content
*/
private function processKeyValueForLoop($matches) {
$keyName = $matches[1];
$valueName = $matches[2];
$arrayPath = $matches[3];
$content = $matches[4];
// Get the array to iterate over
$array = $this->getNestedValue($arrayPath);
// If not an array or empty, return appropriate message
if (!is_array($array)) {
if ($this->debugMode) {
return "<!-- Debug: Array '{$arrayPath}' not found or not an array -->";
}
return '';
}
return $this->processKeyValueLoop($array, $keyName, $valueName, $arrayPath, $content);
}
/**
* Process a loop with an array
*
* @param array $array The array to iterate over
* @param string $itemName The name of the item variable
* @param string $arrayPath The path to the array (for debugging)
* @param string $content The content to process for each iteration
* @return string The processed content
*/
private function processLoop($array, $itemName, $arrayPath, $content) {
$result = '';
$originalVars = $this->variables; // Backup original scope
$arrayLength = count($array);
$index = 0;
foreach ($array as $key => $item) {
$this->checkMemoryUsage();
// Create new scope for this iteration
$iterationVars = $originalVars;
$iterationVars[$itemName] = $item;
// Add loop metadata
$iterationVars['loop'] = [
'index' => $index + 1,
'first' => ($index === 0),
'last' => ($index === $arrayLength - 1),
'length' => $arrayLength,
'parent' => isset($originalVars['loop']) ? $originalVars['loop'] : null
];
// Set the current scope for variable replacement
$this->variables = $iterationVars;
// Process the content for this iteration
$processedContent = $content;
// Process nested loops first
$processedContent = $this->processForLoops($processedContent);
// Process if conditions
$processedContent = $this->processIfConditions($processedContent);
// Process variables
$processedContent = $this->processVariablesInContent($processedContent);
$result .= $processedContent;
$index++;
}
// Restore original variables scope
$this->variables = $originalVars;
return $result;
}
/**
* Get a property from an item (array or object)
*
* @param mixed $item The item to get the property from
* @param string $property The property path (e.g. "colors.0", "features")
* @return mixed The property value
*/
private function getPropertyFromItem($item, $property) {
$parts = explode('.', $property);
$current = $item;
foreach ($parts as $part) {
if (is_array($current) && array_key_exists($part, $current)) {
$current = $current[$part];
} elseif (is_object($current) && property_exists($current, $part)) {
$current = $current->$part;
} else {
if ($this->debugMode) {
$type = is_object($current) ? get_class($current) : gettype($current);
error_log("Template Debug: Property '{$part}' not found in {$type}");
}
return null;
}
}
return $current;
}
/**
* Process a key-value loop (for key, value in array)
*/
private function processKeyValueLoop($array, $keyName, $valueName, $arrayPath, $content) {
$result = '';
$originalVars = $this->variables; // Backup original scope
$arrayLength = count($array);
$index = 0;
foreach ($array as $key => $value) {
$this->checkMemoryUsage();
// Create new scope for this iteration
$iterationVars = $originalVars;
$iterationVars[$keyName] = $key;
$iterationVars[$valueName] = $value;
// Add loop metadata
$iterationVars['loop'] = [
'index' => $index + 1,
'first' => ($index === 0),
'last' => ($index === $arrayLength - 1),
'length' => $arrayLength,
'parent' => isset($originalVars['loop']) ? $originalVars['loop'] : null
];
// Set the current scope for variable replacement
$this->variables = $iterationVars;
// Process the content for this iteration
$processedContent = $content;
// Process nested loops first
$processedContent = $this->processForLoops($processedContent);
// Process if conditions
$processedContent = $this->processIfConditions($processedContent);
// Process variables
$processedContent = $this->processVariablesInContent($processedContent);
$result .= $processedContent;
$index++;
}
// Restore original variables scope
$this->variables = $originalVars;
return $result;
}
/**
* Process if conditions in templates
*
* @param string $template The template to process
* @return string The processed template
*/
private function processIfConditions($template) {
$iteration = 0;
$lastTemplate = '';
while ($template !== $lastTemplate && $iteration < $this->maxIterations) {
$this->checkMemoryUsage();
$lastTemplate = $template;
// First, process if-else blocks (simpler case)
$template = preg_replace_callback(
'/\{%\s*if\s+(.+?)\s*%\}(.*?)(?:\{%\s*else\s*%\}(.*?))?\{%\s*endif\s*%\}/s',
array($this, 'processSimpleCondition'),
$template
);
// Then process if-elseif-else blocks (more complex case)
$template = preg_replace_callback(
'/\{%\s*if\s+(.+?)\s*%\}(.*?)(?:\{%\s*elseif\s+(.+?)\s*%\}(.*?))*(?:\{%\s*else\s*%\}(.*?))?\{%\s*endif\s*%\}/s',
array($this, 'processComplexCondition'),
$template
);
$iteration++;
}
return $template;
}
/**
* Process a simple if-else condition
*
* @param array $matches Regex matches from preg_replace_callback
* @return string The processed content based on the condition
*/
private function processSimpleCondition($matches) {
$condition = $matches[1];
$ifContent = isset($matches[2]) ? $matches[2] : '';
$elseContent = isset($matches[3]) ? $matches[3] : '';
try {
$result = $this->evaluateCondition($condition);
if ($result) {
return $this->processTemplate($ifContent);
} else {
return $this->processTemplate($elseContent);
}
} catch (Exception $e) {
if ($this->errorMode === 'exception') {
throw $e;
} elseif ($this->errorMode === 'comment') {
return "<!-- Error processing condition '{$condition}': " .
htmlspecialchars($e->getMessage()) . " -->";
}
return '';
}
}
/**
* Process a complex if-elseif-else condition
*
* @param array $matches Regex matches from preg_replace_callback
* @return string The processed content based on the conditions
*/
private function processComplexCondition($matches) {
$ifCondition = $matches[1];
$ifContent = isset($matches[2]) ? $matches[2] : '';
try {
// Check if condition
if ($this->evaluateCondition($ifCondition)) {
return $this->processTemplate($ifContent);
}
// Check for elseif conditions
$fullMatch = $matches[0];
if (preg_match_all('/\{%\s*elseif\s+(.+?)\s*%\}(.*?)(?=\{%\s*(?:elseif|else|endif)\s*%\})/s', $fullMatch, $elseifMatches, PREG_SET_ORDER)) {
foreach ($elseifMatches as $elseifMatch) {
$elseifCondition = $elseifMatch[1];
$elseifContent = $elseifMatch[2];
if ($this->evaluateCondition($elseifCondition)) {
return $this->processTemplate($elseifContent);
}
}
}
// Check for else content
if (preg_match('/\{%\s*else\s*%\}(.*?)(?=\{%\s*endif\s*%\})/s', $fullMatch, $elseMatch)) {
$elseContent = $elseMatch[1];
return $this->processTemplate($elseContent);
}
return '';
} catch (Exception $e) {
if ($this->errorMode === 'exception') {
throw $e;
} elseif ($this->errorMode === 'comment') {
return "<!-- Error processing complex condition: " .
htmlspecialchars($e->getMessage()) . " -->";
}
return '';
}
}
/**
* Evaluate a condition expression
*
* @param string $condition The condition to evaluate
* @return bool The result of the evaluation
*/
private function evaluateCondition($condition) {
// Replace variables in the condition with their values
$condition = preg_replace_callback(
'/([a-zA-Z0-9._\[\]]+)/',
array($this, 'replaceConditionVariable'),
$condition
);
// Replace operators for PHP evaluation
$condition = str_replace('===', '==', $condition);
$condition = str_replace('!==', '!=', $condition);
// Convert logical operators to PHP syntax
$condition = str_replace(' and ', ' && ', $condition);
$condition = str_replace(' or ', ' || ', $condition);
$condition = str_replace(' not ', ' !', $condition);
// Convert boolean literals to PHP syntax
$condition = str_replace(' true', ' true', $condition);
$condition = str_replace(' false', ' false', $condition);
// Evaluate the condition safely
try {
// Add error suppression to prevent warnings
$result = @eval("return (bool)($condition);");
// If eval failed, return false
if ($result === false && error_get_last() !== null) {
if ($this->debugMode) {
error_log("Template Debug: Failed to evaluate condition: '{$condition}'");
}
return false;
}
return $result;
} catch (Exception $e) {
if ($this->debugMode) {
error_log("Template Debug: Error evaluating condition '{$condition}': " . $e->getMessage());
}
return false;
}
}
/**
* Replace variables in condition expressions
*
* @param array $matches Regex matches from preg_replace_callback
* @return string The value of the variable or the original string if not a variable
*/
private function replaceConditionVariable($matches) {
$path = $matches[1];
// Skip operators and literals
$operators = ['and', 'or', 'not', 'true', 'false', 'null'];
if (is_numeric($path) || in_array(strtolower($path), $operators)) {
return $path;
}
// Handle string literals
if (preg_match('/^["\'].*["\']$/', $path)) {
return $path;
}
// Get the value of the variable
$value = $this->getNestedValue($path);
// Handle null values
if ($value === null) {
return 'null';
}
// Handle boolean values
if (is_bool($value)) {
return $value ? 'true' : 'false';
}
// Handle numeric values
if (is_numeric($value)) {
return $value;
}
// Handle string values
if (is_string($value)) {
return "'" . addslashes($value) . "'";
}
// Handle array values
if (is_array($value)) {
return !empty($value) ? 'true' : 'false';
}
// Handle object values
if (is_object($value)) {
return 'true';
}
return 'null';
}
/**
* Helper method to process variables in content
*/
private function processVariablesInContent($content) {
// Process variables with bracket notation first
$content = preg_replace_callback(
'/\{\{\s*([a-zA-Z0-9_]+(?:\[[^\]]+\])+(?:\.[a-zA-Z0-9_]+)*)\s*\}\}/',
array($this, 'replaceVariable'),
$content
);
// Process regular variables (must come after bracket notation)
$content = preg_replace_callback(
'/\{\{\s*([a-zA-Z0-9._\[\]\'\"]+)\s*\}\}/',
array($this, 'replaceVariable'),
$content
);
return $content;
}
/**
* Replace a variable with its value
*
* @param array $matches Regex matches from preg_replace_callback
* @return string The value of the variable
*/
private function replaceVariable($matches) {
$path = $matches[1];
// Special case for .length
if (preg_match('/^([a-zA-Z0-9_\.]+)\.length$/', $path, $lenMatch)) {
$arr = $this->getNestedValue($lenMatch[1]);
if (is_array($arr)) {
return count($arr);
} else {
if ($this->debugMode) {
return "<!-- Debug: Variable '{$path}' not found or not an array -->";
}
return '';
}
}
try {
// Handle direct variable access first (no dots)
if (strpos($path, '.') === false && strpos($path, '[') === false) {
if (array_key_exists($path, $this->variables)) {
$value = $this->variables[$path];
// Prevent direct array output
if (is_array($value)) {
if ($this->debugMode) {
return "<!-- Debug: Cannot directly output array '{$path}'. Use a for loop instead. -->";
}
return '';
}
return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
} else {
// Debug output for troubleshooting
if ($this->debugMode) {
return "<!-- Debug: Variable '{$path}' not found -->";
}
return '';
}
}
// Handle nested properties
$value = $this->getNestedValue($path);
// Handle null values
if ($value === null) {
if ($this->debugMode) {
return "<!-- Debug: Variable '{$path}' not found -->";
}
return '';
}
// Prevent direct array output
if (is_array($value)) {
if ($this->debugMode) {
return "<!-- Debug: Cannot directly output array '{$path}'. Use a for loop instead. -->";
}
return '';
}
return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
} catch (Exception $e) {
if ($this->debugMode) {
return '<!-- Error processing variable ' . htmlspecialchars($path) . ': ' .
htmlspecialchars($e->getMessage()) . ' -->';
}
return '';
}
}
/**
* Get a nested value from the variables array using dot and bracket notation
*
* @param string $path The path to the value (e.g. "user.details.balance" or "user[details][balance]")
* @return mixed The value at the path or null if not found
*/
private function getNestedValue($path) {
try {
// Handle empty path
if (empty($path)) {
return null;
}
// Handle direct variable access (no dots or brackets)
if (strpos($path, '.') === false && strpos($path, '[') === false) {
return array_key_exists($path, $this->variables) ? $this->variables[$path] : null;
}
// Normalize path by handling mixed notation (brackets and dots)
$path = preg_replace_callback(
'/\[([^\[\]]+)\]/',
function($match) {
return '.' . trim($match[1], '\'"');
},
$path
);
// Split the path into parts
$parts = explode('.', $path);
$firstPart = array_shift($parts);
// Check if the first part exists in current variables scope
if (!array_key_exists($firstPart, $this->variables)) {
return null;
}
// Start with the first part from current variables scope
$current = $this->variables[$firstPart];
// Traverse the path
foreach ($parts as $part) {
if (empty($part)) continue;
// Handle array access
if (is_array($current) && array_key_exists($part, $current)) {
$current = $current[$part];
}
// Handle object access
elseif (is_object($current) && property_exists($current, $part)) {
$current = $current->$part;
}
// Handle numeric indices for arrays
elseif (is_array($current) && is_numeric($part) && isset($current[(int)$part])) {
$current = $current[(int)$part];
}
// Handle special case for loop variables
elseif ($firstPart === 'loop' && $part === 'parent' && isset($this->variables['loop']['parent'])) {
$current = $this->variables['loop']['parent'];
}
else {
// Debug output for troubleshooting
if ($this->debugMode) {
$type = is_object($current) ? get_class($current) : gettype($current);
error_log("Template Debug: Property '{$part}' not found in {$type} for path '{$path}'");
}
return null;
}
}
return $current;
} catch (Exception $e) {
if ($this->debugMode) {
error_log("Template Debug: Error getting nested value for '{$path}': " . $e->getMessage());
}
return null;
}
}
/**
* Process include statements in templates
*
* @param array $matches Regex matches from preg_replace_callback
* @return string The processed include content
*/
private function processFunction($matches) {
$functionName = 'inc';
$arguments = $matches[1];
// Currently only supporting the inc() function
if ($functionName === 'inc') {
// Extract the template name from the arguments
if (preg_match('/[\'"]([^\'"]+)[\'"]/', $arguments, $argMatches)) {
return $this->processInclude([0, $argMatches[1]]);
}
}
if ($this->debugMode) {
return "<!-- Unknown function: {$functionName}() -->";
}
return '';
}
/**
* Process include statements in templates
*
* @param array $matches Regex matches from preg_replace_callback
* @return string The processed include content
*/
private function processInclude($matches) {
$includeName = $matches[1];
$includePath = $this->templateDir . $includeName . '.' . $this->templateExt;
if (!file_exists($includePath)) {
if ($this->debugMode) {
return "<!-- Include file not found: {$includePath} : Process include statements in templates -->";
}
return '';
}
try {
$includeContent = file_get_contents($includePath);
// Process the included template with the current variables
return $this->processTemplate($includeContent);
} catch (Exception $e) {
if ($this->errorMode === 'exception') {
throw $e;
} elseif ($this->errorMode === 'comment') {
return "<!-- Error processing include '{$includeName}': " .
htmlspecialchars($e->getMessage()) . " -->";
}
return '';
}
}
/**
* Clean up the template by removing any remaining template tags and extra whitespace
*
* @param string $template The template to clean up
* @return string The cleaned template
*/
private function cleanupTemplate($template) {
// Remove any remaining template tags (for safety)
$template = preg_replace('/\{%.*?%\}/', '', $template);
// Optionally, you could also remove extra whitespace here
// $template = preg_replace('/\s+/', ' ', $template);
return $template;
}
/**
* Check if memory usage is approaching the limit and throw an exception if necessary
*
* @throws Exception if memory usage exceeds the limit
*/
private function checkMemoryUsage() {
$memoryUsage = memory_get_usage(true);
$memoryLimit = $this->maxMemory;
// If memory usage is over 90% of the limit, throw an exception
if ($memoryUsage > ($memoryLimit * 0.9)) {
throw new Exception("Memory usage limit approaching: {$memoryUsage} bytes used of {$memoryLimit} bytes allowed");
}
}
/**
* Set debug mode
*
* @param bool $debugMode
* @return Template For method chaining
*/
public function setDebugMode($debugMode) {
$this->debugMode = $debugMode;
return $this;
}
/**
* Set error mode
*
* @param string $errorMode 'comment', 'exception', or 'silent'
* @return Template For method chaining
*/
public function setErrorMode($errorMode) {
if (in_array($errorMode, ['comment', 'exception', 'silent'])) {
$this->errorMode = $errorMode;
}
return $this;
}
/**
* Set maximum memory usage
*
* @param int $maxMemory Maximum memory usage in bytes
* @return Template For method chaining
*/
public function setMaxMemory($maxMemory) {
$this->maxMemory = (int)$maxMemory;
return $this;
}
/**
* Set maximum iterations for recursive template processing
*
* @param int $maxIterations Maximum iterations
* @return Template For method chaining
*/
public function setMaxIterations($maxIterations) {
$this->maxIterations = (int)$maxIterations;
return $this;
}
/**
* Process function calls with parameters
*
* @param array $matches Regex matches from preg_replace_callback
* @return string The result of the function call
*/
private function processFunctionCall($matches) {
$functionName = $matches[1];
$argsString = $matches[2];
// List of allowed functions for security
$allowedFunctions = [
'htmlspecialchars', 'htmlentities', 'strip_tags',
'strtoupper', 'strtolower', 'ucfirst', 'lcfirst', 'ucwords',
'number_format', 'round', 'floor', 'ceil', 'abs',
'count', 'sizeof', 'implode', 'explode', 'trim', 'ltrim', 'rtrim',
'date', 'time', 'strtotime', 'nl2br', 'json_encode', 'md5', 'sha1',
'isset', 'empty', 'is_array', 'is_string', 'is_numeric', 'is_object'
];