template.class.php 10 KB

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