You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

150 lines
4.2 KiB

<?php
/**
* Простейший шаблонизатор.
* Зато быстрый.
*
* @copyright NetMonsters <team@netmonsters.ru>
* @link
* @package Majestic
* @subpackage Decorator
* @since
* @version SVN: $Id$
* @filesource $URL$
*/
final class Sublimer
{
const GLOBAL_KEY = 0;
public $vars = array();
public $path = '';
public $template = '';
protected $head_array = array();
/**
* Конструктор
*
* @param string $path - путь до шаблонов
*/
public function __construct($path = '')
{
$this->setPath($path);
$this->vars[self::GLOBAL_KEY] = array();
}
/**
* Присвоить переменную только
*
* @param string $name - имя переменной
* @param mixed $value - значение переменной
* @param string $template - шаблон, если не указан, то переменная глобальная
*/
public function assign($name, $value, $template = self::GLOBAL_KEY)
{
$this->vars[$template][$name] = $value;
}
/**
* Очистить стек переменных
* @param boolean $with_local - включая локальные переменные
*/
public function clear($template = self::GLOBAL_KEY)
{
$this->vars[$template] = array();
}
/**
* Обработать шаблон
*
* @param string $template - относительный путь до шаблона
* @return string - обработанное содержимое шаблона
*/
public function fetch($template)
{
$this->template = $template; //дабы экстракт не перезатер нам переменную. Это важно! $this то он не перезатрет :)
extract($this->vars[self::GLOBAL_KEY]);
if (isset($this->vars[$this->template])) {
extract($this->vars[$this->template], EXTR_OVERWRITE);
}
ob_start();
if (!(include $this->path.'/'.$this->template) == 'OK') {
throw new MJException('Template '.$this->path.'/'.$this->template.' not found');
}
return ob_get_clean();
}
/**
* Установать путь до шаблонов
*
* @param string $path - путь до шаблонов
*/
public function setPath($path)
{
$this->path = $path;
}
//Функции для вызова из шаблонов.
protected function addHead($str)
{
$this->head_array[] = $str;
}
protected function getHead()
{
return $this->head_array;
}
/**
* обрезает текст до заданной длинны
*
* @param string $text
* @param int $count
* @param string $postfix
*/
protected function trimString($text, $count = 15, $postfix = "...")
{
return (mb_strlen($text) > $count) ? mb_substr($text, 0, $count).$postfix : $text;
}
/**
* Выполняет разрыв строки на данное количество символов с использованием символа разрыва (wordwrap для utf)
*
* @param string $text
* @param int $width
* @param string $break
* @return string
*/
protected function wrapString($text, $width = 15, $break = " ")
{
$words = explode(' ', $text);
for ($i = 0; $i < count($words); $i++) {
if (mb_strlen($words[$i]) > $width) {
for ($j = $width; $j < mb_strlen($words[$i]); $j += $width + (mb_strlen($break))) {
$words[$i] = mb_substr($words[$i], 0, $j) . $break . mb_substr($words[$i], $j);
}
}
}
return implode(' ', $words);
}
function formGet(Array $replaces)
{
$get = $_GET; //дабы не менять дефолтный массив
foreach($replaces as $key => $val) {
$get[$key] = $val;
}
$str = '?';
foreach($get as $key => $val)
{
$str .= $key.'='.$val.'&';
}
return mb_substr($str, 0, -1);
}
}
?>