template.class.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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\}/iU',
  38. 'existelse'=>'/\{#exist ([^}]*)\}([\S\s]*)\{#else \1\}([\S\s]*)\{\/exist \1\}/iU',
  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. if(count($matches) > 2){
  97. $args = [];
  98. foreach(explode('&', $matches[2]) as $chunk){
  99. $param = explode('=', $chunk);
  100. if($param){
  101. $args[urldecode($param[0])] = urldecode($param[1]);
  102. }
  103. }
  104. $widget = "<?php \$widget_parent[] = \$data; \$data = array_merge(\$data, unserialize(".json_encode(serialize($args)).")); ?>";
  105. $widget .= static::compile($widgets[$name]);
  106. $widget .= "<?php \$data = array_pop(\$widget_parent); ?>";
  107. }else{
  108. $widget = $widgets[$name];
  109. }
  110. return $widget;
  111. }, $output);
  112. }
  113. },
  114. 'each'=>function(&$output){
  115. $output = preg_replace_callback(static::$regex['each'], function($matches){
  116. $output = "<?php if(isset(\$data[".var_export($matches[1], true)."])): ";
  117. $output .= "foreach(\$data[".var_export($matches[1], true)."] as \$item): ";
  118. $output .= "\$parent[] = \$data; \$data = \$item; ?>";
  119. $output .= static::compile($matches[2]);
  120. $output .= "<?php \$data = array_pop(\$parent);";
  121. $output .= "endforeach;endif; ?>";
  122. return $output;
  123. }, $output);
  124. },
  125. 'existelse'=>function(&$output){
  126. $output = preg_replace_callback(static::$regex['existelse'], function($matches){
  127. $output = "<?php if(isset(\$data[".var_export($matches[1], true)."])): ?>";
  128. $output .= static::compile($matches[2]);
  129. $output .= "<?php else: ?>";
  130. $output .= static::compile($matches[3]);
  131. $output .= "<?php endif; ?>";
  132. return $output;
  133. }, $output);
  134. },
  135. 'exist'=>function(&$output){
  136. $output = preg_replace_callback(static::$regex['exist'], function($matches){
  137. $output = "<?php if(isset(\$data[".var_export($matches[1], true)."])): ?>";
  138. $output .= static::compile($matches[2]);
  139. $output .= "<?php endif; ?>";
  140. return $output;
  141. }, $output);
  142. },
  143. 'gettext'=>function(&$output){
  144. $output = preg_replace_callback(static::$regex['gettext'], function($matches){
  145. if(count($matches) > 2){
  146. $output = "<?=htmlentities(sprintf(_({$matches[1]})";
  147. foreach(array_slice($matches, 2) as $item){
  148. if(preg_match(static::$regex['gettext_string'], $item)){
  149. $output .= ", $item";
  150. }else{
  151. $output .= ", (\$data['{$item}'] ?? '')";
  152. }
  153. }
  154. }else{
  155. $output = "<?=htmlentities(_({$matches[1]}";
  156. }
  157. return "{$output})); ?>";
  158. }, $output);
  159. },
  160. 'echo'=>function(&$output){
  161. $output = preg_replace_callback(static::$regex['echo'], function($matches){
  162. return "<?= {$matches[1]}; ?>";
  163. }, $output);
  164. },
  165. 'eval'=>function(&$output){
  166. $output = preg_replace_callback(static::$regex['eval'], function($matches){
  167. return "<?php {$matches[1]}; ?>";
  168. }, $output);
  169. },
  170. 'rawmatch'=>function(&$output){
  171. $output = preg_replace_callback(static::$regex['rawmatch'], function($matches){
  172. return "<?=(\$data[".var_export($matches[1], true)."] ?? '');?>";
  173. }, $output);
  174. },
  175. 'rawparentmatch'=>function(&$output){
  176. $output = preg_replace_callback(static::$regex['rawparentmatch'], function($matches){
  177. return "<?=(\$parent[count(\$parent)-1][".var_export($matches[1], true)."] ?? '');?>";
  178. }, $output);
  179. },
  180. 'match'=>function(&$output){
  181. $output = preg_replace_callback(static::$regex['match'], function($matches){
  182. return "<?=htmlentities(\$data[".var_export($matches[1], true)."] ?? '');?>";
  183. }, $output);
  184. },
  185. 'parentmatch'=>function(&$output){
  186. $output = preg_replace_callback(static::$regex['parentmatch'], function($matches){
  187. return "<?=htmlentities(\$parent[count(\$parent)-1][".var_export($matches[1], true)."] ?? '');?>";
  188. }, $output);
  189. },
  190. 'ignored'=>function(&$output, $ignored){
  191. $output = preg_replace_callback(static::$regex['ignored'], function($matches) use($ignored){
  192. return htmlentities($ignored[(int)$matches[1]] ?? '');
  193. }, $output);
  194. }
  195. ];
  196. }
  197. if(isset(static::$templates[$name])){
  198. throw new Exception("Template {$name} already exists");
  199. }
  200. if($is_file){
  201. $path = realpath($template);
  202. if(!file_exists($path)){
  203. throw new Exception("Template file {$template} doesn't exist");
  204. }
  205. $template = file_get_contents($path);
  206. }
  207. static::$parsers['include']($template);
  208. $widgets = [];
  209. static::$parsers['define']($template, $widgets);
  210. static::$parsers['widget']($template, $widgets);
  211. $this->template = $template;
  212. $this->name = $name;
  213. $this->path = static::$cachedir."/{$this->name}.".md5($this->template).'.php';
  214. static::$templates[$name] = $this;
  215. }
  216. public function __get(string $name){
  217. switch($name){
  218. case 'name':case 'template':case 'path':
  219. return $this->$name;
  220. break;
  221. default:
  222. throw new \Exception("Property {$name} doesn't exist");
  223. }
  224. }
  225. public function to_file(){
  226. file_put_contents($this->path, static::compile($this->template));
  227. }
  228. public function run(array $data) : string{
  229. $data = EArray::from($data);
  230. if($this->fire('before', $data) === false){
  231. throw new Exception("Render on template {$this->name} cancelled. Before.");
  232. }
  233. if(!file_exists($this->path)){
  234. $this->to_file();
  235. }
  236. try{
  237. $output = static::execute($this->path, $data);
  238. }catch(Exception $e){
  239. $this->to_file();
  240. $output = static::execute($this->path, $data);
  241. }
  242. if(class_exists('tidy')){
  243. if(is_null(static::$tidy)){
  244. static::$tidy = new \tidy();
  245. }
  246. $tidy = static::$tidy;
  247. $tidy->parseString($output, static::$tidyConfig);
  248. if(!$tidy->cleanRepair()){
  249. throw new \Exception($tidy->errorBuffer);
  250. }
  251. $output = "{$tidy}";
  252. }
  253. if($this->fire('after', $output) === false){
  254. throw new Exception("Render on template {$this->name} cancelled. After");
  255. }
  256. return (string)$output;
  257. }
  258. public static function from(string $name, array $data = []) : string{
  259. $template = static::get($name);
  260. if(is_null($template)){
  261. throw new Exception("Template {$name} does not exist");
  262. }
  263. return $template->run($data);
  264. }
  265. public static function get(string $name){
  266. return static::$templates[$name] ?? null;
  267. }
  268. public static function compile(string $template) : string{
  269. $ignored = [];
  270. $output = $template;
  271. // Handle {#ignore code}
  272. static::$parsers['ignore']($output, $ignored);
  273. // Handle {#include path/to/file}
  274. static::$parsers['include']($output, $ignored);
  275. // Handle {#each name}{/each}
  276. static::$parsers['each']($output);
  277. // Handle {#exist name}{#else}{/exist}
  278. static::$parsers['existelse']($output);
  279. // Handle {#exist name}{/exist}
  280. static::$parsers['exist']($output);
  281. // Handle {gettext}
  282. static::$parsers['gettext']($output);
  283. // Handle {=expression}
  284. static::$parsers['echo']($output);
  285. // Handle {? expression ?}
  286. static::$parsers['eval']($output);
  287. // Handle {@../name}
  288. static::$parsers['rawparentmatch']($output);
  289. // Handle {@name}
  290. static::$parsers['rawmatch']($output);
  291. // Handle {../name}
  292. static::$parsers['parentmatch']($output);
  293. // Handle {name}
  294. static::$parsers['match']($output);
  295. // Handle {#ignored i}
  296. static::$parsers['ignored']($output, $ignored);
  297. return $output;
  298. }
  299. public static function parse(string $template, $data) : string{
  300. $id = md5($template);
  301. if(!isset(static::$templates[$id])){
  302. new Template($id, $template);
  303. }
  304. return static::$templates[$id]->run($data);
  305. }
  306. public static function execute(string $path, $data) : string{
  307. ob_start();
  308. include($path);
  309. $output = ob_get_contents();
  310. ob_end_clean();
  311. return $output;
  312. }
  313. public static function templates(){
  314. return static::$templates;
  315. }
  316. }
  317. ?>