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

  1. <?php
  2. /**
  3. * Простейший шаблонизатор.
  4. * Зато быстрый.
  5. *
  6. * @copyright NetMonsters <team@netmonsters.ru>
  7. * @link
  8. * @package Majestic
  9. * @subpackage Decorator
  10. * @since
  11. * @version SVN: $Id$
  12. * @filesource $URL$
  13. */
  14. final class Sublimer
  15. {
  16. const GLOBAL_KEY = 0;
  17. public $vars = array();
  18. public $path = '';
  19. public $template = '';
  20. protected $head_array = array();
  21. /**
  22. * Конструктор
  23. *
  24. * @param string $path - путь до шаблонов
  25. */
  26. public function __construct($path = '')
  27. {
  28. $this->setPath($path);
  29. $this->vars[self::GLOBAL_KEY] = array();
  30. }
  31. /**
  32. * Присвоить переменную только
  33. *
  34. * @param string $name - имя переменной
  35. * @param mixed $value - значение переменной
  36. * @param string $template - шаблон, если не указан, то переменная глобальная
  37. */
  38. public function assign($name, $value, $template = self::GLOBAL_KEY)
  39. {
  40. $this->vars[$template][$name] = $value;
  41. }
  42. /**
  43. * Очистить стек переменных
  44. * @param boolean $with_local - включая локальные переменные
  45. */
  46. public function clear($template = self::GLOBAL_KEY)
  47. {
  48. $this->vars[$template] = array();
  49. }
  50. /**
  51. * Обработать шаблон
  52. *
  53. * @param string $template - относительный путь до шаблона
  54. * @return string - обработанное содержимое шаблона
  55. */
  56. public function fetch($template)
  57. {
  58. $this->template = $template; //дабы экстракт не перезатер нам переменную. Это важно! $this то он не перезатрет :)
  59. extract($this->vars[self::GLOBAL_KEY]);
  60. if (isset($this->vars[$this->template])) {
  61. extract($this->vars[$this->template], EXTR_OVERWRITE);
  62. }
  63. ob_start();
  64. if (!(include $this->path.'/'.$this->template) == 'OK') {
  65. throw new MJException('Template '.$this->path.'/'.$this->template.' not found');
  66. }
  67. return ob_get_clean();
  68. }
  69. /**
  70. * Установать путь до шаблонов
  71. *
  72. * @param string $path - путь до шаблонов
  73. */
  74. public function setPath($path)
  75. {
  76. $this->path = $path;
  77. }
  78. //Функции для вызова из шаблонов.
  79. protected function addHead($str)
  80. {
  81. $this->head_array[] = $str;
  82. }
  83. protected function getHead()
  84. {
  85. return $this->head_array;
  86. }
  87. /**
  88. * обрезает текст до заданной длинны
  89. *
  90. * @param string $text
  91. * @param int $count
  92. * @param string $postfix
  93. */
  94. protected function trimString($text, $count = 15, $postfix = "...")
  95. {
  96. return (mb_strlen($text) > $count) ? mb_substr($text, 0, $count).$postfix : $text;
  97. }
  98. /**
  99. * Выполняет разрыв строки на данное количество символов с использованием символа разрыва (wordwrap для utf)
  100. *
  101. * @param string $text
  102. * @param int $width
  103. * @param string $break
  104. * @return string
  105. */
  106. protected function wrapString($text, $width = 15, $break = " ")
  107. {
  108. $words = explode(' ', $text);
  109. for ($i = 0; $i < count($words); $i++) {
  110. if (mb_strlen($words[$i]) > $width) {
  111. for ($j = $width; $j < mb_strlen($words[$i]); $j += $width + (mb_strlen($break))) {
  112. $words[$i] = mb_substr($words[$i], 0, $j) . $break . mb_substr($words[$i], $j);
  113. }
  114. }
  115. }
  116. return implode(' ', $words);
  117. }
  118. function formGet(Array $replaces)
  119. {
  120. $get = $_GET; //дабы не менять дефолтный массив
  121. foreach($replaces as $key => $val) {
  122. $get[$key] = $val;
  123. }
  124. $str = '?';
  125. foreach($get as $key => $val)
  126. {
  127. $str .= $key.'='.$val.'&';
  128. }
  129. return mb_substr($str, 0, -1);
  130. }
  131. }
  132. ?>