PageRenderTime 42ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/libs/mustache/mustache/src/Mustache/Compiler.php

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