Compiler.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. <?php
  2. /*
  3. * This file is part of Mustache.php.
  4. *
  5. * (c) 2012 Justin Hileman
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. /**
  11. * Mustache Compiler class.
  12. *
  13. * This class is responsible for turning a Mustache token parse tree into normal PHP source code.
  14. */
  15. class Mustache_Compiler
  16. {
  17. private $sections;
  18. private $source;
  19. private $indentNextLine;
  20. private $customEscape;
  21. private $entityFlags;
  22. private $charset;
  23. private $strictCallables;
  24. private $pragmas;
  25. /**
  26. * Compile a Mustache token parse tree into PHP source code.
  27. *
  28. * @param string $source Mustache Template source code
  29. * @param string $tree Parse tree of Mustache tokens
  30. * @param string $name Mustache Template class name
  31. * @param bool $customEscape (default: false)
  32. * @param int $entityFlags (default: ENT_COMPAT)
  33. * @param string $charset (default: 'UTF-8')
  34. * @param bool $strictCallables (default: false)
  35. *
  36. * @return string Generated PHP source code
  37. */
  38. public function compile($source, array $tree, $name, $customEscape = false, $charset = 'UTF-8', $strictCallables = false, $entityFlags = ENT_COMPAT)
  39. {
  40. $this->pragmas = array();
  41. $this->sections = array();
  42. $this->source = $source;
  43. $this->indentNextLine = true;
  44. $this->customEscape = $customEscape;
  45. $this->entityFlags = $entityFlags;
  46. $this->charset = $charset;
  47. $this->strictCallables = $strictCallables;
  48. return $this->writeCode($tree, $name);
  49. }
  50. /**
  51. * Helper function for walking the Mustache token parse tree.
  52. *
  53. * @throws Mustache_Exception_SyntaxException upon encountering unknown token types.
  54. *
  55. * @param array $tree Parse tree of Mustache tokens
  56. * @param int $level (default: 0)
  57. *
  58. * @return string Generated PHP source code
  59. */
  60. private function walk(array $tree, $level = 0)
  61. {
  62. $code = '';
  63. $level++;
  64. foreach ($tree as $node) {
  65. switch ($node[Mustache_Tokenizer::TYPE]) {
  66. case Mustache_Tokenizer::T_PRAGMA:
  67. $this->pragmas[$node[Mustache_Tokenizer::NAME]] = true;
  68. break;
  69. case Mustache_Tokenizer::T_SECTION:
  70. $code .= $this->section(
  71. $node[Mustache_Tokenizer::NODES],
  72. $node[Mustache_Tokenizer::NAME],
  73. $node[Mustache_Tokenizer::INDEX],
  74. $node[Mustache_Tokenizer::END],
  75. $node[Mustache_Tokenizer::OTAG],
  76. $node[Mustache_Tokenizer::CTAG],
  77. $level
  78. );
  79. break;
  80. case Mustache_Tokenizer::T_INVERTED:
  81. $code .= $this->invertedSection(
  82. $node[Mustache_Tokenizer::NODES],
  83. $node[Mustache_Tokenizer::NAME],
  84. $level
  85. );
  86. break;
  87. case Mustache_Tokenizer::T_PARTIAL:
  88. case Mustache_Tokenizer::T_PARTIAL_2:
  89. $code .= $this->partial(
  90. $node[Mustache_Tokenizer::NAME],
  91. isset($node[Mustache_Tokenizer::INDENT]) ? $node[Mustache_Tokenizer::INDENT] : '',
  92. $level
  93. );
  94. break;
  95. case Mustache_Tokenizer::T_UNESCAPED:
  96. case Mustache_Tokenizer::T_UNESCAPED_2:
  97. $code .= $this->variable($node[Mustache_Tokenizer::NAME], false, $level);
  98. break;
  99. case Mustache_Tokenizer::T_COMMENT:
  100. break;
  101. case Mustache_Tokenizer::T_ESCAPED:
  102. $code .= $this->variable($node[Mustache_Tokenizer::NAME], true, $level);
  103. break;
  104. case Mustache_Tokenizer::T_TEXT:
  105. $code .= $this->text($node[Mustache_Tokenizer::VALUE], $level);
  106. break;
  107. default:
  108. throw new Mustache_Exception_SyntaxException(sprintf('Unknown token type: %s', $node[Mustache_Tokenizer::TYPE]), $node);
  109. }
  110. }
  111. return $code;
  112. }
  113. const KLASS = '<?php
  114. class %s extends Mustache_Template
  115. {
  116. private $lambdaHelper;%s
  117. public function renderInternal(Mustache_Context $context, $indent = \'\')
  118. {
  119. $this->lambdaHelper = new Mustache_LambdaHelper($this->mustache, $context);
  120. $buffer = \'\';
  121. %s
  122. return $buffer;
  123. }
  124. %s
  125. }';
  126. const KLASS_NO_LAMBDAS = '<?php
  127. class %s extends Mustache_Template
  128. {%s
  129. public function renderInternal(Mustache_Context $context, $indent = \'\')
  130. {
  131. $buffer = \'\';
  132. %s
  133. return $buffer;
  134. }
  135. }';
  136. const STRICT_CALLABLE = 'protected $strictCallables = true;';
  137. /**
  138. * Generate Mustache Template class PHP source.
  139. *
  140. * @param array $tree Parse tree of Mustache tokens
  141. * @param string $name Mustache Template class name
  142. *
  143. * @return string Generated PHP source code
  144. */
  145. private function writeCode($tree, $name)
  146. {
  147. $code = $this->walk($tree);
  148. $sections = implode("\n", $this->sections);
  149. $klass = empty($this->sections) ? self::KLASS_NO_LAMBDAS : self::KLASS;
  150. $callable = $this->strictCallables ? $this->prepare(self::STRICT_CALLABLE) : '';
  151. return sprintf($this->prepare($klass, 0, false, true), $name, $callable, $code, $sections);
  152. }
  153. const SECTION_CALL = '
  154. // %s section
  155. $buffer .= $this->section%s($context, $indent, $context->%s(%s));
  156. ';
  157. const SECTION = '
  158. private function section%s(Mustache_Context $context, $indent, $value)
  159. {
  160. $buffer = \'\';
  161. if (%s) {
  162. $source = %s;
  163. $buffer .= $this->mustache
  164. ->loadLambda((string) call_user_func($value, $source, $this->lambdaHelper)%s)
  165. ->renderInternal($context, $indent);
  166. } elseif (!empty($value)) {
  167. $values = $this->isIterable($value) ? $value : array($value);
  168. foreach ($values as $value) {
  169. $context->push($value);%s
  170. $context->pop();
  171. }
  172. }
  173. return $buffer;
  174. }';
  175. /**
  176. * Generate Mustache Template section PHP source.
  177. *
  178. * @param array $nodes Array of child tokens
  179. * @param string $id Section name
  180. * @param int $start Section start offset
  181. * @param int $end Section end offset
  182. * @param string $otag Current Mustache opening tag
  183. * @param string $ctag Current Mustache closing tag
  184. * @param int $level
  185. *
  186. * @return string Generated section PHP source code
  187. */
  188. private function section($nodes, $id, $start, $end, $otag, $ctag, $level)
  189. {
  190. $method = $this->getFindMethod($id);
  191. $id = var_export($id, true);
  192. $source = var_export(substr($this->source, $start, $end - $start), true);
  193. $callable = $this->getCallable();
  194. if ($otag !== '{{' || $ctag !== '}}') {
  195. $delims = ', '.var_export(sprintf('{{= %s %s =}}', $otag, $ctag), true);
  196. } else {
  197. $delims = '';
  198. }
  199. $key = ucfirst(md5($delims."\n".$source));
  200. if (!isset($this->sections[$key])) {
  201. $this->sections[$key] = sprintf($this->prepare(self::SECTION), $key, $callable, $source, $delims, $this->walk($nodes, 2));
  202. }
  203. return sprintf($this->prepare(self::SECTION_CALL, $level), $id, $key, $method, $id);
  204. }
  205. const INVERTED_SECTION = '
  206. // %s inverted section
  207. $value = $context->%s(%s);
  208. if (empty($value)) {
  209. %s
  210. }';
  211. /**
  212. * Generate Mustache Template inverted section PHP source.
  213. *
  214. * @param array $nodes Array of child tokens
  215. * @param string $id Section name
  216. * @param int $level
  217. *
  218. * @return string Generated inverted section PHP source code
  219. */
  220. private function invertedSection($nodes, $id, $level)
  221. {
  222. $method = $this->getFindMethod($id);
  223. $id = var_export($id, true);
  224. return sprintf($this->prepare(self::INVERTED_SECTION, $level), $id, $method, $id, $this->walk($nodes, $level));
  225. }
  226. const PARTIAL = '
  227. if ($partial = $this->mustache->loadPartial(%s)) {
  228. $buffer .= $partial->renderInternal($context, %s);
  229. }
  230. ';
  231. /**
  232. * Generate Mustache Template partial call PHP source.
  233. *
  234. * @param string $id Partial name
  235. * @param string $indent Whitespace indent to apply to partial
  236. * @param int $level
  237. *
  238. * @return string Generated partial call PHP source code
  239. */
  240. private function partial($id, $indent, $level)
  241. {
  242. return sprintf(
  243. $this->prepare(self::PARTIAL, $level),
  244. var_export($id, true),
  245. var_export($indent, true)
  246. );
  247. }
  248. const VARIABLE = '
  249. $value = $this->resolveValue($context->%s(%s), $context, $indent);%s
  250. $buffer .= %s%s;
  251. ';
  252. /**
  253. * Generate Mustache Template variable interpolation PHP source.
  254. *
  255. * @param string $id Variable name
  256. * @param boolean $escape Escape the variable value for output?
  257. * @param int $level
  258. *
  259. * @return string Generated variable interpolation PHP source
  260. */
  261. private function variable($id, $escape, $level)
  262. {
  263. $filters = '';
  264. if (isset($this->pragmas[Mustache_Engine::PRAGMA_FILTERS])) {
  265. list($id, $filters) = $this->getFilters($id, $level);
  266. }
  267. $method = $this->getFindMethod($id);
  268. $id = ($method !== 'last') ? var_export($id, true) : '';
  269. $value = $escape ? $this->getEscape() : '$value';
  270. return sprintf($this->prepare(self::VARIABLE, $level), $method, $id, $filters, $this->flushIndent(), $value);
  271. }
  272. /**
  273. * Generate Mustache Template variable filtering PHP source.
  274. *
  275. * @param string $id Variable name
  276. * @param int $level
  277. *
  278. * @return string Generated variable filtering PHP source
  279. */
  280. private function getFilters($id, $level)
  281. {
  282. $filters = array_map('trim', explode('|', $id));
  283. $id = array_shift($filters);
  284. return array($id, $this->getFilter($filters, $level));
  285. }
  286. const FILTER = '
  287. $filter = $context->%s(%s);
  288. if (!(%s)) {
  289. throw new Mustache_Exception_UnknownFilterException(%s);
  290. }
  291. $value = call_user_func($filter, $value);%s
  292. ';
  293. /**
  294. * Generate PHP source for a single filter.
  295. *
  296. * @param array $filters
  297. * @param int $level
  298. *
  299. * @return string Generated filter PHP source
  300. */
  301. private function getFilter(array $filters, $level)
  302. {
  303. if (empty($filters)) {
  304. return '';
  305. }
  306. $name = array_shift($filters);
  307. $method = $this->getFindMethod($name);
  308. $filter = ($method !== 'last') ? var_export($name, true) : '';
  309. $callable = $this->getCallable('$filter');
  310. $msg = var_export($name, true);
  311. return sprintf($this->prepare(self::FILTER, $level), $method, $filter, $callable, $msg, $this->getFilter($filters, $level));
  312. }
  313. const LINE = '$buffer .= "\n";';
  314. const TEXT = '$buffer .= %s%s;';
  315. /**
  316. * Generate Mustache Template output Buffer call PHP source.
  317. *
  318. * @param string $text
  319. * @param int $level
  320. *
  321. * @return string Generated output Buffer call PHP source
  322. */
  323. private function text($text, $level)
  324. {
  325. $indentNextLine = (substr($text, -1) === "\n");
  326. $code = sprintf($this->prepare(self::TEXT, $level), $this->flushIndent(), var_export($text, true));
  327. $this->indentNextLine = $indentNextLine;
  328. return $code;
  329. }
  330. /**
  331. * Prepare PHP source code snippet for output.
  332. *
  333. * @param string $text
  334. * @param int $bonus Additional indent level (default: 0)
  335. * @param boolean $prependNewline Prepend a newline to the snippet? (default: true)
  336. * @param boolean $appendNewline Append a newline to the snippet? (default: false)
  337. *
  338. * @return string PHP source code snippet
  339. */
  340. private function prepare($text, $bonus = 0, $prependNewline = true, $appendNewline = false)
  341. {
  342. $text = ($prependNewline ? "\n" : '').trim($text);
  343. if ($prependNewline) {
  344. $bonus++;
  345. }
  346. if ($appendNewline) {
  347. $text .= "\n";
  348. }
  349. return preg_replace("/\n( {8})?/", "\n".str_repeat(" ", $bonus * 4), $text);
  350. }
  351. const DEFAULT_ESCAPE = 'htmlspecialchars(%s, %s, %s)';
  352. const CUSTOM_ESCAPE = 'call_user_func($this->mustache->getEscape(), %s)';
  353. /**
  354. * Get the current escaper.
  355. *
  356. * @param string $value (default: '$value')
  357. *
  358. * @return string Either a custom callback, or an inline call to `htmlspecialchars`
  359. */
  360. private function getEscape($value = '$value')
  361. {
  362. if ($this->customEscape) {
  363. return sprintf(self::CUSTOM_ESCAPE, $value);
  364. } else {
  365. return sprintf(self::DEFAULT_ESCAPE, $value, var_export($this->entityFlags, true), var_export($this->charset, true));
  366. }
  367. }
  368. /**
  369. * Select the appropriate Context `find` method for a given $id.
  370. *
  371. * The return value will be one of `find`, `findDot` or `last`.
  372. *
  373. * @see Mustache_Context::find
  374. * @see Mustache_Context::findDot
  375. * @see Mustache_Context::last
  376. *
  377. * @param string $id Variable name
  378. *
  379. * @return string `find` method name
  380. */
  381. private function getFindMethod($id)
  382. {
  383. if ($id === '.') {
  384. return 'last';
  385. } elseif (strpos($id, '.') === false) {
  386. return 'find';
  387. } else {
  388. return 'findDot';
  389. }
  390. }
  391. const IS_CALLABLE = '!is_string(%s) && is_callable(%s)';
  392. const STRICT_IS_CALLABLE = 'is_object(%s) && is_callable(%s)';
  393. private function getCallable($variable = '$value')
  394. {
  395. $tpl = $this->strictCallables ? self::STRICT_IS_CALLABLE : self::IS_CALLABLE;
  396. return sprintf($tpl, $variable, $variable);
  397. }
  398. const LINE_INDENT = '$indent . ';
  399. /**
  400. * Get the current $indent prefix to write to the buffer.
  401. *
  402. * @return string "$indent . " or ""
  403. */
  404. private function flushIndent()
  405. {
  406. if (!$this->indentNextLine) {
  407. return '';
  408. }
  409. $this->indentNextLine = false;
  410. return self::LINE_INDENT;
  411. }
  412. }