template.class.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. 'drop-empty-elements'=>false
  31. ];
  32. private static $regex = [
  33. 'getmatch'=>'/\{!([^#\/?_][^}\n]*?)\}/i',
  34. 'getparentmatch'=>'/\{!\.\.\/([^#\/?_][^}\n]*?)\}/i',
  35. 'getrawmatch'=>'/\{!@([^#\/?_][^}\n]*?)\}/i',
  36. 'getrawparentmatch'=>'/\{!@\.\.\/([^#\/?_][^}\n]*?)\}/i',
  37. 'match'=>'/\{([^#\/?_][^}\n]*?)\}/i',
  38. 'parentmatch'=>'/\{\.\.\/([^#\/?_][^}\n]*?)\}/i',
  39. 'rawmatch'=>'/\{@([^#\/?_][^}\n]*?)\}/i',
  40. 'rawparentmatch'=>'/\{@\.\.\/([^#\/?_][^}\n]*?)\}/i',
  41. 'each'=>'/\{#each ([^}]*)\}([\S\s]*)\{\/each \1\}/i',
  42. 'exist'=>'/\{#exist ([^}]*)\}([\S\s]*)\{\/exist \1\}/iU',
  43. 'existelse'=>'/\{#exist ([^}]*)\}([\S\s]*)\{#else \1\}([\S\s]*)\{\/exist \1\}/iU',
  44. 'ignore'=>'/\{#ignore\}([\S\s]*)\{\/ignore\}/i',
  45. 'ignored'=>'/\{#ignored (\d+?)\}/i',
  46. 'gettext'=>"/{_([^,}]+)(?:, ?([^},]+))*\}/i",
  47. 'gettext_string'=>'/^([\'"])(.+)\1$/i',
  48. 'echo'=>'/\{=([^}]+)\}/i',
  49. 'eval'=>'/\{\?([\W\w\S\s]+)\?\}/i',
  50. 'include'=>'/{#include ([^}]+)}/i',
  51. 'define'=>'/\{#define ([^}]*)\}([\S\s]*)\{\/define \1\}/i',
  52. 'widget'=>'/{#widget ([^ }]+)(?: ((?:[^=}]+=[^}&]*)*))?}/i'
  53. ];
  54. protected static $parsers;
  55. private $template;
  56. private $name;
  57. private $path;
  58. public function __construct(string $name, string $template, bool $is_file = false){
  59. if(is_null(static::$parsers)){
  60. static::$parsers = [
  61. 'ignore'=>function(&$output, &$ignored){
  62. $output = preg_replace_callback(static::$regex['ignore'], function($matches) use(&$ignored){
  63. $ignored[] = $matches[1];
  64. return '{#ignored '.(count($ignored) - 1).'}';
  65. }, $output);
  66. },
  67. 'include'=>function(&$output, &$ignored = null){
  68. while(preg_match(static::$regex['include'], $output)){
  69. $output = preg_replace_callback(static::$regex['include'], function($matches) use(&$ignored){
  70. $path = static::$basedir.'/'.$matches[1];
  71. if(file_exists($path)){
  72. $output = file_get_contents($path);
  73. if(!is_null($ignored)){
  74. static::$parsers['ignore']($output, $ignored);
  75. }
  76. return $output;
  77. }
  78. return '';
  79. }, $output);
  80. }
  81. },
  82. 'define'=>function(&$output, &$widgets){
  83. while(preg_match(static::$regex['define'], $output)){
  84. $output = preg_replace_callback(static::$regex['define'], function($matches) use(&$widgets){
  85. $name = $matches[1];
  86. if(isset($widgets[$name])){
  87. throw new \Exception("Widget {$name} is already defined");
  88. }
  89. $widgets[$name] = $matches[2];
  90. return '';
  91. }, $output);
  92. }
  93. },
  94. 'widget'=>function(&$output, $widgets){
  95. while(preg_match(static::$regex['widget'], $output)){
  96. $output = preg_replace_callback(static::$regex['widget'], function($matches) use(&$widgets){
  97. $name = $matches[1];
  98. if(!isset($widgets[$name])){
  99. throw new \Exception("Widget {$name} is not defined");
  100. }
  101. if(count($matches) > 2){
  102. $args = [];
  103. foreach(explode('&', $matches[2]) as $chunk){
  104. $param = explode('=', $chunk);
  105. if($param){
  106. $val = $param[1] ?? "";
  107. $args[urldecode($param[0])] = urldecode($val);
  108. }
  109. }
  110. $widget = "<?php \$widget_parent[] = \$data; \$data = array_merge(json_decode(json_encode(\$data), true), json_decode(base64_decode(".var_export(base64_encode(json_encode($args)), true)."), true)); ?>";
  111. $widget .= static::compile($widgets[$name]);
  112. $widget .= "<?php \$data = array_pop(\$widget_parent); ?>";
  113. }else{
  114. $widget = $widgets[$name];
  115. }
  116. return $widget;
  117. }, $output);
  118. }
  119. },
  120. 'each'=>function(&$output){
  121. $output = preg_replace_callback(static::$regex['each'], function($matches){
  122. $output = "<?php if(isset(\$data[".var_export($matches[1], true)."])): ";
  123. $output .= "foreach(\$data[".var_export($matches[1], true)."] as \$item): ";
  124. $output .= "\$parent[] = \$data; \$data = \$item; ?>";
  125. $output .= static::compile($matches[2]);
  126. $output .= "<?php \$data = array_pop(\$parent);";
  127. $output .= "endforeach;endif; ?>";
  128. return $output;
  129. }, $output);
  130. },
  131. 'existelse'=>function(&$output){
  132. $output = preg_replace_callback(static::$regex['existelse'], function($matches){
  133. $output = "<?php if(isset(\$data[".var_export($matches[1], true)."])): ?>";
  134. $output .= static::compile($matches[2]);
  135. $output .= "<?php else: ?>";
  136. $output .= static::compile($matches[3]);
  137. $output .= "<?php endif; ?>";
  138. return $output;
  139. }, $output);
  140. },
  141. 'exist'=>function(&$output){
  142. $output = preg_replace_callback(static::$regex['exist'], function($matches){
  143. $output = "<?php if(isset(\$data[".var_export($matches[1], true)."])): ?>";
  144. $output .= static::compile($matches[2]);
  145. $output .= "<?php endif; ?>";
  146. return $output;
  147. }, $output);
  148. },
  149. 'gettext'=>function(&$output){
  150. $output = preg_replace_callback(static::$regex['gettext'], function($matches){
  151. if(count($matches) > 2){
  152. $output = "<?=htmlentities(sprintf(_({$matches[1]})";
  153. foreach(array_slice($matches, 2) as $item){
  154. if(preg_match(static::$regex['gettext_string'], $item)){
  155. $output .= ", $item";
  156. }else{
  157. $output .= ", (\$data['{$item}'] ?? '')";
  158. }
  159. }
  160. }else{
  161. $output = "<?=htmlentities(_({$matches[1]}";
  162. }
  163. return "{$output})); ?>";
  164. }, $output);
  165. },
  166. 'echo'=>function(&$output){
  167. $output = preg_replace_callback(static::$regex['echo'], function($matches){
  168. return "<?= {$matches[1]}; ?>";
  169. }, $output);
  170. },
  171. 'eval'=>function(&$output){
  172. $output = preg_replace_callback(static::$regex['eval'], function($matches){
  173. return "<?php {$matches[1]}; ?>";
  174. }, $output);
  175. },
  176. 'getrawmatch'=>function(&$output){
  177. $output = preg_replace_callback(static::$regex['getrawmatch'], function($matches){
  178. return "<?=(\$data[\$data[".var_export($matches[1], true)."] ?? ''] ?? '');?>";
  179. }, $output);
  180. },
  181. 'getrawparentmatch'=>function(&$output){
  182. $output = preg_replace_callback(static::$regex['getrawparentmatch'], function($matches){
  183. return "<?=(\$parent[count(\$parent)-1][\$data[".var_export($matches[1], true)."] ?? ''] ?? '');?>";
  184. }, $output);
  185. },
  186. 'getmatch'=>function(&$output){
  187. $output = preg_replace_callback(static::$regex['getmatch'], function($matches){
  188. return "<?=htmlentities(\$data[\$data[".var_export($matches[1], true)."] ?? ''] ?? '');?>";
  189. }, $output);
  190. },
  191. 'getparentmatch'=>function(&$output){
  192. $output = preg_replace_callback(static::$regex['getparentmatch'], function($matches){
  193. return "<?=htmlentities(\$parent[count(\$parent)-1][\$data[".var_export($matches[1], true)."] ?? ''] ?? '');?>";
  194. }, $output);
  195. },
  196. 'rawmatch'=>function(&$output){
  197. $output = preg_replace_callback(static::$regex['rawmatch'], function($matches){
  198. return "<?=(\$data[".var_export($matches[1], true)."] ?? '');?>";
  199. }, $output);
  200. },
  201. 'rawparentmatch'=>function(&$output){
  202. $output = preg_replace_callback(static::$regex['rawparentmatch'], function($matches){
  203. return "<?=(\$parent[count(\$parent)-1][".var_export($matches[1], true)."] ?? '');?>";
  204. }, $output);
  205. },
  206. 'match'=>function(&$output){
  207. $output = preg_replace_callback(static::$regex['match'], function($matches){
  208. return "<?=htmlentities(\$data[".var_export($matches[1], true)."] ?? '');?>";
  209. }, $output);
  210. },
  211. 'parentmatch'=>function(&$output){
  212. $output = preg_replace_callback(static::$regex['parentmatch'], function($matches){
  213. return "<?=htmlentities(\$parent[count(\$parent)-1][".var_export($matches[1], true)."] ?? '');?>";
  214. }, $output);
  215. },
  216. 'ignored'=>function(&$output, $ignored){
  217. $output = preg_replace_callback(static::$regex['ignored'], function($matches) use($ignored){
  218. return htmlentities($ignored[(int)$matches[1]] ?? '');
  219. }, $output);
  220. }
  221. ];
  222. }
  223. if(isset(static::$templates[$name])){
  224. throw new Exception("Template {$name} already exists");
  225. }
  226. if($is_file){
  227. $path = realpath($template);
  228. if(!file_exists($path)){
  229. throw new Exception("Template file {$template} doesn't exist");
  230. }
  231. $template = file_get_contents($path);
  232. }
  233. static::$parsers['include']($template);
  234. $widgets = [];
  235. static::$parsers['define']($template, $widgets);
  236. static::$parsers['widget']($template, $widgets);
  237. $this->template = $template;
  238. $this->name = $name;
  239. $this->path = static::$cachedir."/{$this->name}.".md5($this->template).'.php';
  240. static::$templates[$name] = $this;
  241. }
  242. public function __get(string $name){
  243. switch($name){
  244. case 'name':case 'template':case 'path':
  245. return $this->$name;
  246. break;
  247. default:
  248. throw new \Exception("Property {$name} doesn't exist");
  249. }
  250. }
  251. public function to_file(){
  252. file_put_contents($this->path, static::compile($this->template));
  253. }
  254. public function run(array $data) : string{
  255. $data = EArray::from($data);
  256. if($this->fire('before', $data) === false){
  257. throw new Exception("Render on template {$this->name} cancelled. Before.");
  258. }
  259. if(!file_exists($this->path)){
  260. $this->to_file();
  261. }
  262. try{
  263. $output = static::execute($this->path, $data);
  264. }catch(Exception $e){
  265. $this->to_file();
  266. $output = static::execute($this->path, $data);
  267. }
  268. if(class_exists('tidy')){
  269. if(is_null(static::$tidy)){
  270. static::$tidy = new \tidy();
  271. }
  272. $tidy = static::$tidy;
  273. $tidy->parseString($output, static::$tidyConfig);
  274. if(!$tidy->cleanRepair()){
  275. throw new \Exception($tidy->errorBuffer);
  276. }
  277. $output = "{$tidy}";
  278. }
  279. if($this->fire('after', $output) === false){
  280. throw new Exception("Render on template {$this->name} cancelled. After");
  281. }
  282. return (string)$output;
  283. }
  284. public static function from(string $name, array $data = []) : string{
  285. $template = static::get($name);
  286. if(is_null($template)){
  287. throw new Exception("Template {$name} does not exist");
  288. }
  289. return $template->run($data);
  290. }
  291. public static function get(string $name){
  292. return static::$templates[$name] ?? null;
  293. }
  294. public static function compile(string $template) : string{
  295. $ignored = [];
  296. $output = $template;
  297. // Handle {#ignore code}
  298. static::$parsers['ignore']($output, $ignored);
  299. // Handle {#include path/to/file}
  300. static::$parsers['include']($output, $ignored);
  301. // Handle {#each name}{/each}
  302. static::$parsers['each']($output);
  303. // Handle {#exist name}{#else}{/exist}
  304. static::$parsers['existelse']($output);
  305. // Handle {#exist name}{/exist}
  306. static::$parsers['exist']($output);
  307. // Handle {gettext}
  308. static::$parsers['gettext']($output);
  309. // Handle {=expression}
  310. static::$parsers['echo']($output);
  311. // Handle {? expression ?}
  312. static::$parsers['eval']($output);
  313. // Handle {!@../name}
  314. static::$parsers['getrawparentmatch']($output);
  315. // Handle {!@name}
  316. static::$parsers['getrawmatch']($output);
  317. // Handle {!../name}
  318. static::$parsers['getparentmatch']($output);
  319. // Handle {!name}
  320. static::$parsers['getmatch']($output);
  321. // Handle {@../name}
  322. static::$parsers['rawparentmatch']($output);
  323. // Handle {@name}
  324. static::$parsers['rawmatch']($output);
  325. // Handle {../name}
  326. static::$parsers['parentmatch']($output);
  327. // Handle {name}
  328. static::$parsers['match']($output);
  329. // Handle {#ignored i}
  330. static::$parsers['ignored']($output, $ignored);
  331. return $output;
  332. }
  333. public static function parse(string $template, $data) : string{
  334. $id = md5($template);
  335. if(!isset(static::$templates[$id])){
  336. new Template($id, $template);
  337. }
  338. return static::$templates[$id]->run($data);
  339. }
  340. public static function execute(string $path, $data) : string{
  341. ob_start();
  342. include($path);
  343. $output = ob_get_contents();
  344. ob_end_clean();
  345. return $output;
  346. }
  347. public static function templates(){
  348. return static::$templates;
  349. }
  350. }
  351. ?>