template.class.php 13 KB

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