<?php
/* Please see the README and LICENSE files. */
/**
* This class tokenizes, then replacesa some block of text
*/
class Template_Parser {
/**
* The text to parse
* @var String
*/
protected $text;
/**
* The tokens found in the text
* @var Template_Token[]
*/
protected $tokens;
/**
* The text after replacing the tokens
* @var String
*/
protected $parsed_text;
/**
* Make new instance, store the text
* @param String $text
*/
public function __construct($text) {
$this->text = $text;
}
/**
* Parse the text
* @param String[] $vars Variables in the template
* @param Data_Model $model A data model to get data from
* @return String The parsed text
*/
public function parse($vars=NULL, $model=NULL) {
$this->get_tokens();
$this->parsed_text = $this->text;
if (is_array($this->tokens)) {
foreach ($this->tokens as $token) {
$token->parse($vars, $model);
$this->parsed_text = str_replace($token->text, $token->parsed, $this->parsed_text);
}
}
return $this->parsed_text;
}
protected function get_tokens() {
$cache_name = "template_" . md5($this->text);
if (!($cached_object = Cache_Subsystem::cache_get($cache_name, Cache_Subsystem::CONTROLLER_FILE)) === false) {
}
if ($cached_object instanceof $this) {
$this->tokens = $cached_object->tokens;
return;
}
// Not in cache, tokenize
if (!isset($this->tokens)) {
$tfact = new Template_TokenFactory();
$this->tokens = $tfact->tokenize($this->text);
}
if ($cached_object === false) {
Cache_Subsystem::cache($cache_name, $this, 3600, Cache_Subsystem::CONTROLLER_FILE);
}
}
function __get($name) {
if (property_exists($this, $name)) {
return $this->$name;
}
}
}
?>