Files
majestic/classes/Sublimer.class.php
akulikov fe9034fd92 formGet method enchanted !no!ticket!number!
git-svn-id: svn+ssh://code.netmonsters.ru/svn/majestic/trunk@99 4cb57b5f-5bbd-dd11-951b-001d605cbbc5
2009-06-03 13:20:09 +00:00

176 lines
5.3 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?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);
}
/**
* Формирует get-строку для запроса
*
* @param array/string $replace - Имя переменной для замены (либо массив ключ=значение) В случае false вернет весь get
* @param mixed $value - значение переменной для замены, если $replace - массив, то не играет роли. В случае false переменная удаляется из get
* @return string
*/
function formGet($replace = false, $value = false)
{
$chunk = true; //обрезать последний & (или ?)
$get = $_GET; //дабы не менять дефолтный массив
if (is_array($replace)) {
foreach($replace as $key => $val) {
if($val === false) {
unset($get[$key]);
$chunk = false;
} else {
$get[$key] = $val;
}
}
} else if ($replace !== false) {
if ($value === false) { //для получения строки БЕЗ параметра с именем $replace
unset($get[$replace]);
$chunk = false;
} else {
$get[$replace] = $value;
}
}
$str = '?';
foreach($get as $key => $val) {
$str .= $key.'='.$val.'&';
}
if ($chunk) {
$str = mb_substr($str, 0, -1);
}
return htmlspecialchars($str);
}
}
?>