class TemplateCompiler static function Compile Template global Theme I

 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
class TemplateCompiler
{
static function Compile($Template)
{
global $Theme;
$Id = md5($Template);
$Template = $Theme.'/templates/'.$Template.'.html';
if(is_file($Template))
{
$File = 'cache/templates/'.$Id;
if(is_file($File) && filemtime($File) != filemtime($Template))
{
return $Id;
}
$Template = file_get_contents($Template);
$Patterns = array('/\{%([a-z0-9]+)(\[.*\])*\}/im', '/\[%([a-z0-9]+)(\[.*\])*\]/im', '/\{[\s]*if[\s]+%([a-z0-9]+)(\[.*\])*[\s]*\}/im', '/\{[\s]*elseif[\s]+%([a-z0-9]+)(\[.*\])*[\s]*\}/im', '/\{[\s]*foreach[\s]+%([a-z0-9]+)(\[.*\])*[\s]+as[\s]+%([a-z0-9]+)[\s]*\}/im', '/\{[\s]*for[\s]+%([a-z0-9]+)[\s]*=[\s]*([\d]+)[\s]*;[\s]*%([a-z0-9]+)[\s]*([=<>!]+)[\s]*([\d]+)[\s]*;[\s]*%([a-z0-9\+\-]+)[\s]*\}/im', '/\{[\s]*while[\s]+%([a-z0-9]+)(\[.*\])*[\s]*\}/im', '/\{[\s]*switch[\s]+%([a-z0-9]+)(\[.*\])*[\s]*\}/im', '/\{[\s]*case[\s]+([\']?)([^\']+)([\']?)[\s]*\}/im', '/\{[\s]*end[\s]*\}/im');
$Replacements = array('<?php echo $Variables[\'\\1\']\\2 ?>', '<?php echo $\\1\\2 ?>', '<?php if($Variables[\'\\1\']\\2) { ?>', '<?php } elseif($Variables[\'\\1\']\\2) { ?>', '<?php foreach($Variables[\'\\1\']\\2 as $\\3) { ?>', '<?php for($\\1 = \\2; $\\3 \\4 \\5; $\\6) { ?>', '<?php while($Variables[\'\\1\']\\2) { ?>', '<?php switch($Variables[\'\\1\']\\2) { ?>', '<?php case \\1\\2\\3: ?>', '<?php } ?>');
ksort($Patterns);
ksort($Replacements);
$Compiled = preg_replace($Patterns, $Replacements, $Template);
file_put_contents($File, $Compiled);
return $Id;
}
}
static function Template($Template, $Variables)
{
global $Theme;
if(is_file($Theme.'/templates/'.$Template.'.html'))
{
$Id = TemplateCompiler::Compile($Template);
ob_start();
include('cache/templates/'.$Id);
return ob_get_clean();
}
}
static function Display($Template, $Variables)
{
echo TemplateCompiler::Template($Template, $Variables);
}
}