<?php

class View
{
    var $_vars = array();
    var $_tpl = '';

    /**
     * Constructor
     *
     * @param string $tpl template path starting from _inc/
     * @param string $path
     * @return View
     */
    function View($tpl, $path = '')
    {
        $this->setTpl($tpl, $path);
    }

    /**
     * Sets template for the view
     *
     * @param string $tpl template path starting from _inc/
     * @param string $path
     */
    function setTpl($tpl, $path = '')
    {
        if (empty($path)) {
            $this->_tpl = dirname(__FILE__) . '/../views/' . $tpl . '.php';
        } else {
            $this->_tpl =  $path . $tpl . '.php';
        }
    }

    /**
     * Gets var value
     * @param $k var name
     * @return mixed var value
     */
    function getVar($name)
    {
        return (isset($this->_vars[$name]) ? $this->_vars[$name] : '');
    }

    /**
     * Sets var
     * @param string $k name
     * @param mixed $v value
     * @param bool $escape mode
     */
    function setVar($k, $v, $escape=true)
    {
        $this->_vars[$k] = ($escape ? $this->_escape($v) : $v);
    }

    /**
     * Fetchs result into string
     * @return string
     */
    function fetch()
    {
        extract($this->_vars);
        ob_start();
        require $this->_tpl;
        $str = ob_get_clean();
        return $str;
    }

    /** performs html escaping
    */
    function _escape($v)
    {
        if (is_array($v))
            return array_map(array($this, '_escape'), $v);
        if (is_object($v))
            return $v;
        return htmlspecialchars($v, ENT_QUOTES, 'UTF-8');
    }

	public static function encode($text)
	{
		return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
	}
}
?>