1
0

template.class.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. <?php
  2. namespace Juju\Data;
  3. require_once(realpath(dirname(__DIR__).'/events.trait.php'));
  4. require_once('earray.class.php');
  5. use Juju\{Events, Data\EArray};
  6. use \Exception;
  7. class Template {
  8. use Events;
  9. private static $templates = [];
  10. public static $cachedir;
  11. public static $basedir = __DIR__;
  12. private static $tidy;
  13. private static $tidyConfig = [
  14. 'indent'=>true,
  15. 'tab-size'=>4,
  16. 'wrap'=>0,
  17. 'wrap-asp'=>false,
  18. 'wrap-attributes'=>false,
  19. 'wrap-jste'=>false,
  20. 'wrap-php'=>false,
  21. 'wrap-script-literals'=>false,
  22. 'wrap-sections'=>false,
  23. 'char-encoding'=>'utf8',
  24. 'newline'=>'LF',
  25. 'tidy-mark'=>true,
  26. 'merge-divs'=>false,
  27. 'merge-spans'=>false,
  28. 'logical-emphasis'=>false,
  29. 'literal-attributes'=>true
  30. ];
  31. private static $regex = [
  32. 'match'=>'/\{([^#\/?_][^}\n]*?)\}/i',
  33. 'parentmatch'=>'/\{\.\.\/([^#\/?_][^}\n]*?)\}/i',
  34. 'rawmatch'=>'/\{@([^#\/?_][^}\n]*?)\}/i',
  35. 'rawparentmatch'=>'/\{@\.\.\/([^#\/?_][^}\n]*?)\}/i',
  36. 'each'=>'/\{#each ([^}]*)\}([\S\s]*)\{\/each \1\}/i',
  37. 'exist'=>'/\{#exist ([^}]*)\}([\S\s]*)\{\/exist \1\}/i',
  38. 'existelse'=>'/\{#exist ([^}]*)\}([\S\s]*)\{#else \1\}([\S\s]*)\{\/exist \1\}/i',
  39. 'ignore'=>'/\{#ignore\}([\S\s]*)\{\/ignore\}/i',
  40. 'ignored'=>'/\{#ignored (\d+?)\}/i',
  41. 'gettext'=>"/{_([^,}]+)(?:, ?([^},]+))*\}/i",
  42. 'gettext_string'=>'/^([\'"])(.+)\1$/i',
  43. 'echo'=>'/\{=([^}]+)\}/i',
  44. 'eval'=>'/\{\?([\W\w\S\s]+)\?\}/i',
  45. 'include'=>'/{#include ([^}]+)}/i',
  46. 'define'=>'/\{#define ([^}]*)\}([\S\s]*)\{\/define \1\}/i',
  47. 'widget'=>'/{#widget ([^}]+)}/i'
  48. ];
  49. protected static $parsers;
  50. private $template;
  51. private $name;
  52. private $path;
  53. public function __construct(string $name, string $template, bool $is_file = false){
  54. if(is_null(static::$parsers)){
  55. static::$parsers = [
  56. 'ignore'=>function(&$output, &$ignored){
  57. $output = preg_replace_callback(static::$regex['ignore'], function($matches) use(&$ignored){
  58. $ignored[] = $matches[1];
  59. return '{#ignored '.(count($ignored) - 1).'}';
  60. }, $output);
  61. },
  62. 'include'=>function(&$output, &$ignored = null){
  63. while(preg_match(static::$regex['include'], $output)){
  64. $output = preg_replace_callback(static::$regex['include'], function($matches) use(&$ignored){
  65. $path = static::$basedir.'/'.$matches[1];
  66. if(file_exists($path)){
  67. $output = file_get_contents($path);
  68. if(!is_null($ignored)){
  69. static::$parsers['ignore']($output, $ignored);
  70. }
  71. return $output;
  72. }
  73. return '';
  74. }, $output);
  75. }
  76. },
  77. 'define'=>function(&$output, &$widgets){
  78. while(preg_match(static::$regex['define'], $output)){
  79. $output = preg_replace_callback(static::$regex['define'], function($matches) use(&$widgets){
  80. $name = $matches[1];
  81. if(isset($widgets[$name])){
  82. throw new \Exception("Widget {$name} is already defined");
  83. }
  84. $widgets[$name] = $matches[2];
  85. return '';
  86. }, $output);
  87. }
  88. },
  89. 'widget'=>function(&$output, $widgets){
  90. while(preg_match(static::$regex['widget'], $output)){
  91. $output = preg_replace_callback(static::$regex['widget'], function($matches) use(&$widgets){
  92. $name = $matches[1];
  93. if(!isset($widgets[$name])){
  94. throw new \Exception("Widget {$name} is not defined");
  95. }
  96. return $widgets[$name];
  97. }, $output);
  98. }
  99. },
  100. 'each'=>function(&$output){
  101. $output = preg_replace_callback(static::$regex['each'], function($matches){
  102. $output = "<?php if(isset(\$data[".var_export($matches[1], true)."])): ";
  103. $output .= "foreach(\$data[".var_export($matches[1], true)."] as \$item): ";
  104. $output .= "\$parent[] = \$data; \$data = \$item; ?>";
  105. $output .= static::compile($matches[2]);
  106. $output .= "<?php \$data = array_pop(\$parent);";
  107. $output .= "endforeach;endif; ?>";
  108. return $output;
  109. }, $output);
  110. },
  111. 'existelse'=>function(&$output){
  112. $output = preg_replace_callback(static::$regex['existelse'], function($matches){
  113. $output = "<?php if(isset(\$data[".var_export($matches[1], true)."])): ?>";
  114. $output .= static::compile($matches[2]);
  115. $output .= "<?php else: ?>";
  116. $output .= static::compile($matches[3]);
  117. $output .= "<?php endif; ?>";
  118. return $output;
  119. }, $output);
  120. },
  121. 'exist'=>function(&$output){
  122. $output = preg_replace_callback(static::$regex['exist'], function($matches){
  123. $output = "<?php if(isset(\$data[".var_export($matches[1], true)."])): ?>";
  124. $output .= static::compile($matches[2]);
  125. $output .= "<?php endif; ?>";
  126. return $output;
  127. }, $output);
  128. },
  129. 'gettext'=>function(&$output){
  130. $output = preg_replace_callback(static::$regex['gettext'], function($matches){
  131. if(count($matches) > 2){
  132. $output = "<?=htmlentities(sprintf(_({$matches[1]})";
  133. foreach(array_slice($matches, 2) as $item){
  134. if(preg_match(static::$regex['gettext_string'], $item)){
  135. $output .= ", $item";
  136. }else{
  137. $output .= ", (\$data['{$item}'] ?? '')";
  138. }
  139. }
  140. }else{
  141. $output = "<?=htmlentities(_({$matches[1]}";
  142. }
  143. return "{$output})); ?>";
  144. }, $output);
  145. },
  146. 'echo'=>function(&$output){
  147. $output = preg_replace_callback(static::$regex['echo'], function($matches){
  148. return "<?= {$matches[1]}; ?>";
  149. }, $output);
  150. },
  151. 'eval'=>function(&$output){
  152. $output = preg_replace_callback(static::$regex['eval'], function($matches){
  153. return "<?php {$matches[1]}; ?>";
  154. }, $output);
  155. },
  156. 'rawmatch'=>function(&$output){
  157. $output = preg_replace_callback(static::$regex['rawmatch'], function($matches){
  158. return "<?=(\$data[".var_export($matches[1], true)."] ?? '');?>";
  159. }, $output);
  160. },
  161. 'rawparentmatch'=>function(&$output){
  162. $output = preg_replace_callback(static::$regex['rawparentmatch'], function($matches){
  163. return "<?=(\$parent[count(\$parent)-1][".var_export($matches[1], true)."] ?? '');?>";
  164. }, $output);
  165. },
  166. 'match'=>function(&$output){
  167. $output = preg_replace_callback(static::$regex['match'], function($matches){
  168. return "<?=htmlentities(\$data[".var_export($matches[1], true)."] ?? '');?>";
  169. }, $output);
  170. },
  171. 'parentmatch'=>function(&$output){
  172. $output = preg_replace_callback(static::$regex['parentmatch'], function($matches){
  173. return "<?=htmlentities(\$parent[count(\$parent)-1][".var_export($matches[1], true)."] ?? '');?>";
  174. }, $output);
  175. },
  176. 'ignored'=>function(&$output, $ignored){
  177. $output = preg_replace_callback(static::$regex['ignored'], function($matches) use($ignored){
  178. return htmlentities($ignored[(int)$matches[1]] ?? '');
  179. }, $output);
  180. }
  181. ];
  182. }
  183. if(isset(static::$templates[$name])){
  184. throw new Exception("Template {$name} already exists");
  185. }
  186. if($is_file){
  187. $path = realpath($template);
  188. if(!file_exists($path)){
  189. throw new Exception("Template file {$template} doesn't exist");
  190. }
  191. $template = file_get_contents($path);
  192. }
  193. static::$parsers['include']($template);
  194. $widgets = [];
  195. static::$parsers['define']($template, $widgets);
  196. static::$parsers['widget']($template, $widgets);
  197. $this->template = $template;
  198. $this->name = $name;
  199. $this->path = static::$cachedir."/{$this->name}.".md5($this->template).'.php';
  200. static::$templates[$name] = $this;
  201. }
  202. public function run(array $data) : string{
  203. $data = EArray::from($data);
  204. if($this->fire('before', $data) === false){
  205. throw new Exception("Render on template {$this->name} cancelled. Before.");
  206. }
  207. if(!file_exists($this->path)){
  208. file_put_contents($this->path, static::compile($this->template));
  209. }
  210. try{
  211. $output = static::execute($this->path, $data);
  212. }catch(Exception $e){
  213. file_put_contents($this->path, static::compile($this->template));
  214. $output = static::execute($this->path, $data);
  215. }
  216. if(class_exists('tidy')){
  217. if(is_null(static::$tidy)){
  218. static::$tidy = new \tidy();
  219. }
  220. $tidy = static::$tidy;
  221. $tidy->parseString($output, static::$tidyConfig);
  222. if(!$tidy->cleanRepair()){
  223. throw new \Exception($tidy->errorBuffer);
  224. }
  225. $output = "{$tidy}";
  226. }
  227. if($this->fire('after', $output) === false){
  228. throw new Exception("Render on template {$this->name} cancelled. After");
  229. }
  230. return (string)$output;
  231. }
  232. public static function from(string $name, array $data = []) : string{
  233. $template = static::$templates[$name] ?? null;
  234. if(is_null($template)){
  235. throw new Exception("Template {$name} does not exist");
  236. }
  237. return $template->run($data);
  238. }
  239. public static function compile(string $template) : string{
  240. $ignored = [];
  241. $output = $template;
  242. // Handle {#ignore code}
  243. static::$parsers['ignore']($output, $ignored);
  244. // Handle {#include path/to/file}
  245. static::$parsers['include']($output, $ignored);
  246. // Handle {#each name}{/each}
  247. static::$parsers['each']($output);
  248. // Handle {#exist name}{#else}{/exist}
  249. static::$parsers['existelse']($output);
  250. // Handle {#exist name}{/exist}
  251. static::$parsers['exist']($output);
  252. // Handle {gettext}
  253. static::$parsers['gettext']($output);
  254. // Handle {=expression}
  255. static::$parsers['echo']($output);
  256. // Handle {? expression ?}
  257. static::$parsers['eval']($output);
  258. // Handle {@../name}
  259. static::$parsers['rawparentmatch']($output);
  260. // Handle {@name}
  261. static::$parsers['rawmatch']($output);
  262. // Handle {../name}
  263. static::$parsers['parentmatch']($output);
  264. // Handle {name}
  265. static::$parsers['match']($output);
  266. // Handle {#ignored i}
  267. static::$parsers['ignored']($output, $ignored);
  268. return $output;
  269. }
  270. public static function parse(string $template, $data) : string{
  271. $id = md5($template);
  272. if(!isset(static::$templates[$id])){
  273. new Template($id, $template);
  274. }
  275. return static::$templates[$id]->run($data);
  276. }
  277. public static function execute(string $path, $data) : string{
  278. ob_start();
  279. include($path);
  280. $output = ob_get_contents();
  281. ob_end_clean();
  282. return $output;
  283. }
  284. }
  285. ?>