Skip to content

Instantly share code, notes, and snippets.

@audinue
Created January 28, 2015 06:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save audinue/f3fab0299486ac0378e3 to your computer and use it in GitHub Desktop.
Save audinue/f3fab0299486ac0378e3 to your computer and use it in GitHub Desktop.
SimpleTemplate
<?php
class SimpleTemplate {
function renderString($string, $args = NULL) {
if(is_array($args)) {
$this->validateArgs($args);
extract($args);
}
eval('?>' . $this->parseString($string));
}
function render($file, $args = NULL) {
if(is_array($args)) {
$this->validateArgs($args);
extract($args);
}
eval('?>' . $this->parse($file));
}
function compileString($string, $args = NULL) {
if(is_array($args)) {
$this->validateArgs($args);
extract($args);
}
ob_start();
eval('?>' . $this->parseString($string));
return ob_get_clean();
}
function compile($file, $args = NULL) {
if(is_array($args)) {
$this->validateArgs($args);
extract($args);
}
ob_start();
eval('?>' . $this->parse($file));
return ob_get_clean();
}
private function validateArgs($args) {
if(isset($args['file']) || isset($args['args']) || isset($args['this'])) {
throw new Exception('Invalid arguments.');
}
}
private function parseString($string) {
$string = str_replace("\r", '', $string);
$length = strlen($string);
$result = '';
$state = 0;
for($i = 0; $i < $length; $i++) {
$char = $string[$i];
switch($state) {
case 0:
switch($char) {
case '@':
$result .= '<?php ';
$state = 1;
break;
case '{':
$result .= '<?php ';
$state = 2;
break;
case '\\':
$state = 8;
break;
default:
$result .= $char;
}
break;
case 1:
if($char == "\n") {
$result .= ' ?>' . $char;
$state = 0;
} else {
$result .= $char;
}
break;
case 2:
switch($char) {
case '{':
$state = 3;
break;
case '=':
$result .= 'echo ';
$state = 4;
break;
case '?':
$result .= 'echo urlencode(';
$state = 5;
break;
default:
$result .= 'echo htmlspecialchars(' . $char;
$state = 6;
}
break;
case 3:
if($char == '}') {
$state = 7;
} else {
$result .= $char;
}
break;
case 4:
if($char == '}') {
$result .= ' ?>';
$state = 0;
} else {
$result .= $char;
}
break;
case 5:
case 6:
if($char == '}') {
$result .= ') ?>';
$state = 0;
} else {
$result .= $char;
}
break;
case 7:
if($char == '}') {
$result .= ' ?>';
$state = 0;
} else {
$result .= '}' . $char;
$state = 3;
}
break;
case 8:
switch($char) {
case '@':
$result .= $char;
$state = 0;
break;
case '{':
$result .= $char;
$state = 0;
break;
case '\\':
$result .= '\\' . $char;
$state = 0;
break;
}
break;
}
}
return $result;
}
private function parse($file) {
if(!is_file($file)) {
throw new Exception('Template file "' . $file . '" is not found.');
}
return $this->parseString(
file_get_contents($file)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment