<?php
/**
 * 紫斑马软件
 * @author afan
 * @link http://www.zibanma.com
 */
if(ZIBANMA_SYS_LINK != 'zibanma_com'){
	die('access deny');
}
class ZibanmaView{
	private static $view;
	private $view_root;
	private $templateName;
	private $content;
	private $eval;
	private $start_execute = '<?php';
	private $assign = array();
	private $error = array();
	
	private function __construct(){
		$this->view_root = ZIBANMA_SYS_APP_ROOT.'/template/';
	}
	
	public static function get_instance(){
		if(!(self::$view instanceof self)){
			self::$view = new self();
		}
		return self::$view;
	}
	
	private function is_exists(){
		if(!file_exists($this->templateName.'.php')){
			$this->error[] = '模板文件不存在';
			return false;
		}
		return true;
	}
	
	private function set_content(){
		if($this->is_exists()){
			$this->content = file_get_contents($this->templateName.'.php');
		}else{
			$this->error[] = '模板文件读取错误';
		}
	}
	
	public function set_replace(){
		$this->content = str_replace($this->start_execute, '{zibanma_php}', $this->content);
		$this->content = str_replace('<?=', '{zibanma_php} echo', $this->content);
		$this->content = str_replace('<?', '{zibanma_php}', $this->content);
		$this->content = str_replace('{zibanma_php}', $this->start_execute, $this->content);
	}	
	
	private function set_eval(){
		if($this->assign){
			foreach ($this->assign as $key=>$val){
				$$key = $val;
			}
		}
		$this->is_access();
		$this->set_replace();
		$this->eval = eval(' ?>'.$this->content.'<?php ');
	}
	
	public function is_access(){
		if(strpos($this->content, 'zibanma_com') === false){
			$this->error[] = '访问控制失效，模板已对外访问开放';
		}
	}
	
	public function make($templateName, $assign=array()){
		$this->assign = $assign;
		$this->templateName = $this->view_root.str_replace('.', '/', $templateName);
		$this->set_content();
		$this->set_eval();
		$this->out_error();
		return $this->eval;
	}
	
	public function get_error(){
		return $this->error;
	}
	
	public function out_error(){
		$info = array();
		if(count($this->error)>0){
			$info[] = '<li>模板错误：</li>';
			foreach ($this->get_error() as $ev){
				$info[] = '<li>'.$ev.'</li>';
			}
			echo implode('', $info);
		}
	}
}
?>