Mustache.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. <?php
  2. /**
  3. * A Mustache implementation in PHP.
  4. *
  5. * {@link http://defunkt.github.com/mustache}
  6. *
  7. * Mustache is a framework-agnostic logic-less templating language. It enforces separation of view
  8. * logic from template files. In fact, it is not even possible to embed logic in the template.
  9. *
  10. * This is very, very rad.
  11. *
  12. * @author Justin Hileman {@link http://justinhileman.com}
  13. */
  14. class Mustache {
  15. const VERSION = '0.9.0';
  16. const SPEC_VERSION = '1.1.2';
  17. /**
  18. * Should this Mustache throw exceptions when it finds unexpected tags?
  19. *
  20. * @see self::_throwsException()
  21. */
  22. protected $_throwsExceptions = array(
  23. MustacheException::UNKNOWN_VARIABLE => false,
  24. MustacheException::UNCLOSED_SECTION => true,
  25. MustacheException::UNEXPECTED_CLOSE_SECTION => true,
  26. MustacheException::UNKNOWN_PARTIAL => false,
  27. MustacheException::UNKNOWN_PRAGMA => true,
  28. );
  29. // Override charset passed to htmlentities() and htmlspecialchars(). Defaults to UTF-8.
  30. protected $_charset = 'UTF-8';
  31. /**
  32. * Pragmas are macro-like directives that, when invoked, change the behavior or
  33. * syntax of Mustache.
  34. *
  35. * They should be considered extremely experimental. Most likely their implementation
  36. * will change in the future.
  37. */
  38. /**
  39. * The {{%UNESCAPED}} pragma swaps the meaning of the {{normal}} and {{{unescaped}}}
  40. * Mustache tags. That is, once this pragma is activated the {{normal}} tag will not be
  41. * escaped while the {{{unescaped}}} tag will be escaped.
  42. *
  43. * Pragmas apply only to the current template. Partials, even those included after the
  44. * {{%UNESCAPED}} call, will need their own pragma declaration.
  45. *
  46. * This may be useful in non-HTML Mustache situations.
  47. */
  48. const PRAGMA_UNESCAPED = 'UNESCAPED';
  49. /**
  50. * Constants used for section and tag RegEx
  51. */
  52. const SECTION_TYPES = '\^#\/';
  53. const TAG_TYPES = '#\^\/=!<>\\{&';
  54. protected $_otag = '{{';
  55. protected $_ctag = '}}';
  56. protected $_tagRegEx;
  57. protected $_template = '';
  58. protected $_context = array();
  59. protected $_partials = array();
  60. protected $_pragmas = array();
  61. protected $_pragmasImplemented = array(
  62. self::PRAGMA_UNESCAPED
  63. );
  64. protected $_localPragmas = array();
  65. /**
  66. * Mustache class constructor.
  67. *
  68. * This method accepts a $template string and a $view object. Optionally, pass an associative
  69. * array of partials as well.
  70. *
  71. * Passing an $options array allows overriding certain Mustache options during instantiation:
  72. *
  73. * $options = array(
  74. * // `charset` -- must be supported by `htmlspecialentities()`. defaults to 'UTF-8'
  75. * 'charset' => 'ISO-8859-1',
  76. *
  77. * // opening and closing delimiters, as an array or a space-separated string
  78. * 'delimiters' => '<% %>',
  79. *
  80. * // an array of pragmas to enable/disable
  81. * 'pragmas' => array(
  82. * Mustache::PRAGMA_UNESCAPED => true
  83. * ),
  84. *
  85. * // an array of thrown exceptions to enable/disable
  86. * 'throws_exceptions' => array(
  87. * MustacheException::UNKNOWN_VARIABLE => false,
  88. * MustacheException::UNCLOSED_SECTION => true,
  89. * MustacheException::UNEXPECTED_CLOSE_SECTION => true,
  90. * MustacheException::UNKNOWN_PARTIAL => false,
  91. * MustacheException::UNKNOWN_PRAGMA => true,
  92. * ),
  93. * );
  94. *
  95. * @access public
  96. * @param string $template (default: null)
  97. * @param mixed $view (default: null)
  98. * @param array $partials (default: null)
  99. * @param array $options (default: array())
  100. * @return void
  101. */
  102. public function __construct($template = null, $view = null, $partials = null, array $options = null) {
  103. if ($template !== null) $this->_template = $template;
  104. if ($partials !== null) $this->_partials = $partials;
  105. if ($view !== null) $this->_context = array($view);
  106. if ($options !== null) $this->_setOptions($options);
  107. }
  108. /**
  109. * Helper function for setting options from constructor args.
  110. *
  111. * @access protected
  112. * @param array $options
  113. * @return void
  114. */
  115. protected function _setOptions(array $options) {
  116. if (isset($options['charset'])) {
  117. $this->_charset = $options['charset'];
  118. }
  119. if (isset($options['delimiters'])) {
  120. $delims = $options['delimiters'];
  121. if (!is_array($delims)) {
  122. $delims = array_map('trim', explode(' ', $delims, 2));
  123. }
  124. $this->_otag = $delims[0];
  125. $this->_ctag = $delims[1];
  126. }
  127. if (isset($options['pragmas'])) {
  128. foreach ($options['pragmas'] as $pragma_name => $pragma_value) {
  129. if (!in_array($pragma_name, $this->_pragmasImplemented, true)) {
  130. throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
  131. }
  132. }
  133. $this->_pragmas = $options['pragmas'];
  134. }
  135. if (isset($options['throws_exceptions'])) {
  136. foreach ($options['throws_exceptions'] as $exception => $value) {
  137. $this->_throwsExceptions[$exception] = $value;
  138. }
  139. }
  140. }
  141. /**
  142. * Mustache class clone method.
  143. *
  144. * A cloned Mustache instance should have pragmas, delimeters and root context
  145. * reset to default values.
  146. *
  147. * @access public
  148. * @return void
  149. */
  150. public function __clone() {
  151. $this->_otag = '{{';
  152. $this->_ctag = '}}';
  153. $this->_localPragmas = array();
  154. if ($keys = array_keys($this->_context)) {
  155. $last = array_pop($keys);
  156. if ($this->_context[$last] instanceof Mustache) {
  157. $this->_context[$last] =& $this;
  158. }
  159. }
  160. }
  161. /**
  162. * Render the given template and view object.
  163. *
  164. * Defaults to the template and view passed to the class constructor unless a new one is provided.
  165. * Optionally, pass an associative array of partials as well.
  166. *
  167. * @access public
  168. * @param string $template (default: null)
  169. * @param mixed $view (default: null)
  170. * @param array $partials (default: null)
  171. * @return string Rendered Mustache template.
  172. */
  173. public function render($template = null, $view = null, $partials = null) {
  174. if ($template === null) $template = $this->_template;
  175. if ($partials !== null) $this->_partials = $partials;
  176. $otag_orig = $this->_otag;
  177. $ctag_orig = $this->_ctag;
  178. if ($view) {
  179. $this->_context = array($view);
  180. } else if (empty($this->_context)) {
  181. $this->_context = array($this);
  182. }
  183. $template = $this->_renderPragmas($template);
  184. $template = $this->_renderTemplate($template);
  185. $this->_otag = $otag_orig;
  186. $this->_ctag = $ctag_orig;
  187. return $template;
  188. }
  189. /**
  190. * Wrap the render() function for string conversion.
  191. *
  192. * @access public
  193. * @return string
  194. */
  195. public function __toString() {
  196. // PHP doesn't like exceptions in __toString.
  197. // catch any exceptions and convert them to strings.
  198. try {
  199. $result = $this->render();
  200. return $result;
  201. } catch (Exception $e) {
  202. return "Error rendering mustache: " . $e->getMessage();
  203. }
  204. }
  205. /**
  206. * Internal render function, used for recursive calls.
  207. *
  208. * @access protected
  209. * @param string $template
  210. * @return string Rendered Mustache template.
  211. */
  212. protected function _renderTemplate($template) {
  213. if ($section = $this->_findSection($template)) {
  214. list($before, $type, $tag_name, $content, $after) = $section;
  215. $rendered_before = $this->_renderTags($before);
  216. $rendered_content = '';
  217. $val = $this->_getVariable($tag_name);
  218. switch($type) {
  219. // inverted section
  220. case '^':
  221. if (empty($val)) {
  222. $rendered_content = $this->_renderTemplate($content);
  223. }
  224. break;
  225. // regular section
  226. case '#':
  227. // higher order sections
  228. if ($this->_varIsCallable($val)) {
  229. $rendered_content = $this->_renderTemplate(call_user_func($val, $content));
  230. } else if ($this->_varIsIterable($val)) {
  231. foreach ($val as $local_context) {
  232. $this->_pushContext($local_context);
  233. $rendered_content .= $this->_renderTemplate($content);
  234. $this->_popContext();
  235. }
  236. } else if ($val) {
  237. if (is_array($val) || is_object($val)) {
  238. $this->_pushContext($val);
  239. $rendered_content = $this->_renderTemplate($content);
  240. $this->_popContext();
  241. } else {
  242. $rendered_content = $this->_renderTemplate($content);
  243. }
  244. }
  245. break;
  246. }
  247. return $rendered_before . $rendered_content . $this->_renderTemplate($after);
  248. }
  249. return $this->_renderTags($template);
  250. }
  251. /**
  252. * Prepare a section RegEx string for the given opening/closing tags.
  253. *
  254. * @access protected
  255. * @param string $otag
  256. * @param string $ctag
  257. * @return string
  258. */
  259. protected function _prepareSectionRegEx($otag, $ctag) {
  260. return sprintf(
  261. '/(?:(?<=\\n)[ \\t]*)?%s(?:(?P<type>[%s])(?P<tag_name>.+?)|=(?P<delims>.*?)=)%s\\n?/s',
  262. preg_quote($otag, '/'),
  263. self::SECTION_TYPES,
  264. preg_quote($ctag, '/')
  265. );
  266. }
  267. /**
  268. * Extract the first section from $template.
  269. *
  270. * @access protected
  271. * @param string $template
  272. * @return array $before, $type, $tag_name, $content and $after
  273. */
  274. protected function _findSection($template) {
  275. $regEx = $this->_prepareSectionRegEx($this->_otag, $this->_ctag);
  276. $section_start = null;
  277. $section_type = null;
  278. $content_start = null;
  279. $search_offset = 0;
  280. $section_stack = array();
  281. $matches = array();
  282. while (preg_match($regEx, $template, $matches, PREG_OFFSET_CAPTURE, $search_offset)) {
  283. if (isset($matches['delims'][0])) {
  284. list($otag, $ctag) = explode(' ', $matches['delims'][0]);
  285. $regEx = $this->_prepareSectionRegEx($otag, $ctag);
  286. $search_offset = $matches[0][1] + strlen($matches[0][0]);
  287. continue;
  288. }
  289. $match = $matches[0][0];
  290. $offset = $matches[0][1];
  291. $type = $matches['type'][0];
  292. $tag_name = trim($matches['tag_name'][0]);
  293. $search_offset = $offset + strlen($match);
  294. switch ($type) {
  295. case '^':
  296. case '#':
  297. if (empty($section_stack)) {
  298. $section_start = $offset;
  299. $section_type = $type;
  300. $content_start = $search_offset;
  301. }
  302. array_push($section_stack, $tag_name);
  303. break;
  304. case '/':
  305. if (empty($section_stack) || ($tag_name !== array_pop($section_stack))) {
  306. if ($this->_throwsException(MustacheException::UNEXPECTED_CLOSE_SECTION)) {
  307. throw new MustacheException('Unexpected close section: ' . $tag_name, MustacheException::UNEXPECTED_CLOSE_SECTION);
  308. }
  309. }
  310. if (empty($section_stack)) {
  311. // $before, $type, $tag_name, $content, $after
  312. return array(
  313. substr($template, 0, $section_start),
  314. $section_type,
  315. $tag_name,
  316. substr($template, $content_start, $offset - $content_start),
  317. substr($template, $search_offset),
  318. );
  319. }
  320. break;
  321. }
  322. }
  323. if (!empty($section_stack)) {
  324. if ($this->_throwsException(MustacheException::UNCLOSED_SECTION)) {
  325. throw new MustacheException('Unclosed section: ' . $section_stack[0], MustacheException::UNCLOSED_SECTION);
  326. }
  327. }
  328. }
  329. /**
  330. * Prepare a pragma RegEx for the given opening/closing tags.
  331. *
  332. * @access protected
  333. * @param string $otag
  334. * @param string $ctag
  335. * @return string
  336. */
  337. protected function _preparePragmaRegEx($otag, $ctag) {
  338. return sprintf(
  339. '/%s%%\\s*(?P<pragma_name>[\\w_-]+)(?P<options_string>(?: [\\w]+=[\\w]+)*)\\s*%s\\n?/s',
  340. preg_quote($otag, '/'),
  341. preg_quote($ctag, '/')
  342. );
  343. }
  344. /**
  345. * Initialize pragmas and remove all pragma tags.
  346. *
  347. * @access protected
  348. * @param string $template
  349. * @return string
  350. */
  351. protected function _renderPragmas($template) {
  352. $this->_localPragmas = $this->_pragmas;
  353. // no pragmas
  354. if (strpos($template, $this->_otag . '%') === false) {
  355. return $template;
  356. }
  357. $regEx = $this->_preparePragmaRegEx($this->_otag, $this->_ctag);
  358. return preg_replace_callback($regEx, array($this, '_renderPragma'), $template);
  359. }
  360. /**
  361. * A preg_replace helper to remove {{%PRAGMA}} tags and enable requested pragma.
  362. *
  363. * @access protected
  364. * @param mixed $matches
  365. * @return void
  366. * @throws MustacheException unknown pragma
  367. */
  368. protected function _renderPragma($matches) {
  369. $pragma = $matches[0];
  370. $pragma_name = $matches['pragma_name'];
  371. $options_string = $matches['options_string'];
  372. if (!in_array($pragma_name, $this->_pragmasImplemented)) {
  373. if ($this->_throwsException(MustacheException::UNKNOWN_PRAGMA)) {
  374. throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
  375. } else {
  376. return '';
  377. }
  378. }
  379. $options = array();
  380. foreach (explode(' ', trim($options_string)) as $o) {
  381. if ($p = trim($o)) {
  382. $p = explode('=', $p);
  383. $options[$p[0]] = $p[1];
  384. }
  385. }
  386. if (empty($options)) {
  387. $this->_localPragmas[$pragma_name] = true;
  388. } else {
  389. $this->_localPragmas[$pragma_name] = $options;
  390. }
  391. return '';
  392. }
  393. /**
  394. * Check whether this Mustache has a specific pragma.
  395. *
  396. * @access protected
  397. * @param string $pragma_name
  398. * @return bool
  399. */
  400. protected function _hasPragma($pragma_name) {
  401. if (array_key_exists($pragma_name, $this->_localPragmas) && $this->_localPragmas[$pragma_name]) {
  402. return true;
  403. } else {
  404. return false;
  405. }
  406. }
  407. /**
  408. * Return pragma options, if any.
  409. *
  410. * @access protected
  411. * @param string $pragma_name
  412. * @return mixed
  413. * @throws MustacheException Unknown pragma
  414. */
  415. protected function _getPragmaOptions($pragma_name) {
  416. if (!$this->_hasPragma($pragma_name)) {
  417. if ($this->_throwsException(MustacheException::UNKNOWN_PRAGMA)) {
  418. throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
  419. }
  420. }
  421. return (is_array($this->_localPragmas[$pragma_name])) ? $this->_localPragmas[$pragma_name] : array();
  422. }
  423. /**
  424. * Check whether this Mustache instance throws a given exception.
  425. *
  426. * Expects exceptions to be MustacheException error codes (i.e. class constants).
  427. *
  428. * @access protected
  429. * @param mixed $exception
  430. * @return void
  431. */
  432. protected function _throwsException($exception) {
  433. return (isset($this->_throwsExceptions[$exception]) && $this->_throwsExceptions[$exception]);
  434. }
  435. /**
  436. * Prepare a tag RegEx for the given opening/closing tags.
  437. *
  438. * @access protected
  439. * @param string $otag
  440. * @param string $ctag
  441. * @return string
  442. */
  443. protected function _prepareTagRegEx($otag, $ctag, $first = false) {
  444. return sprintf(
  445. '/(?P<leading>(?:%s\\r?\\n)[ \\t]*)?%s(?P<type>[%s]?)(?P<tag_name>.+?)(?:\\2|})?%s(?P<trailing>\\s*(?:\\r?\\n|\\Z))?/s',
  446. ($first ? '\\A|' : ''),
  447. preg_quote($otag, '/'),
  448. self::TAG_TYPES,
  449. preg_quote($ctag, '/')
  450. );
  451. }
  452. /**
  453. * Loop through and render individual Mustache tags.
  454. *
  455. * @access protected
  456. * @param string $template
  457. * @return void
  458. */
  459. protected function _renderTags($template) {
  460. if (strpos($template, $this->_otag) === false) {
  461. return $template;
  462. }
  463. $first = true;
  464. $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag, true);
  465. $html = '';
  466. $matches = array();
  467. while (preg_match($this->_tagRegEx, $template, $matches, PREG_OFFSET_CAPTURE)) {
  468. $tag = $matches[0][0];
  469. $offset = $matches[0][1];
  470. $modifier = $matches['type'][0];
  471. $tag_name = trim($matches['tag_name'][0]);
  472. if (isset($matches['leading']) && $matches['leading'][1] > -1) {
  473. $leading = $matches['leading'][0];
  474. } else {
  475. $leading = null;
  476. }
  477. if (isset($matches['trailing']) && $matches['trailing'][1] > -1) {
  478. $trailing = $matches['trailing'][0];
  479. } else {
  480. $trailing = null;
  481. }
  482. $html .= substr($template, 0, $offset);
  483. $next_offset = $offset + strlen($tag);
  484. if ((substr($html, -1) == "\n") && (substr($template, $next_offset, 1) == "\n")) {
  485. $next_offset++;
  486. }
  487. $template = substr($template, $next_offset);
  488. $html .= $this->_renderTag($modifier, $tag_name, $leading, $trailing);
  489. if ($first == true) {
  490. $first = false;
  491. $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag);
  492. }
  493. }
  494. return $html . $template;
  495. }
  496. /**
  497. * Render the named tag, given the specified modifier.
  498. *
  499. * Accepted modifiers are `=` (change delimiter), `!` (comment), `>` (partial)
  500. * `{` or `&` (don't escape output), or none (render escaped output).
  501. *
  502. * @access protected
  503. * @param string $modifier
  504. * @param string $tag_name
  505. * @param string $leading Whitespace
  506. * @param string $trailing Whitespace
  507. * @throws MustacheException Unmatched section tag encountered.
  508. * @return string
  509. */
  510. protected function _renderTag($modifier, $tag_name, $leading, $trailing) {
  511. switch ($modifier) {
  512. case '=':
  513. return $this->_changeDelimiter($tag_name, $leading, $trailing);
  514. break;
  515. case '!':
  516. return $this->_renderComment($tag_name, $leading, $trailing);
  517. break;
  518. case '>':
  519. case '<':
  520. return $this->_renderPartial($tag_name, $leading, $trailing);
  521. break;
  522. case '{':
  523. // strip the trailing } ...
  524. if ($tag_name[(strlen($tag_name) - 1)] == '}') {
  525. $tag_name = substr($tag_name, 0, -1);
  526. }
  527. case '&':
  528. if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) {
  529. return $this->_renderEscaped($tag_name, $leading, $trailing);
  530. } else {
  531. return $this->_renderUnescaped($tag_name, $leading, $trailing);
  532. }
  533. break;
  534. case '#':
  535. case '^':
  536. case '/':
  537. // remove any leftover section tags
  538. return $leading . $trailing;
  539. break;
  540. default:
  541. if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) {
  542. return $this->_renderUnescaped($modifier . $tag_name, $leading, $trailing);
  543. } else {
  544. return $this->_renderEscaped($modifier . $tag_name, $leading, $trailing);
  545. }
  546. break;
  547. }
  548. }
  549. /**
  550. * Returns true if any of its args contains the "\r" character.
  551. *
  552. * @access protected
  553. * @param string $str
  554. * @return boolean
  555. */
  556. protected function _stringHasR($str) {
  557. foreach (func_get_args() as $arg) {
  558. if (strpos($arg, "\r") !== false) {
  559. return true;
  560. }
  561. }
  562. return false;
  563. }
  564. /**
  565. * Escape and return the requested tag.
  566. *
  567. * @access protected
  568. * @param string $tag_name
  569. * @param string $leading Whitespace
  570. * @param string $trailing Whitespace
  571. * @return string
  572. */
  573. protected function _renderEscaped($tag_name, $leading, $trailing) {
  574. $rendered = htmlentities($this->_renderUnescaped($tag_name, '', ''), ENT_COMPAT, $this->_charset);
  575. return $leading . $rendered . $trailing;
  576. }
  577. /**
  578. * Render a comment (i.e. return an empty string).
  579. *
  580. * @access protected
  581. * @param string $tag_name
  582. * @param string $leading Whitespace
  583. * @param string $trailing Whitespace
  584. * @return string
  585. */
  586. protected function _renderComment($tag_name, $leading, $trailing) {
  587. if ($leading !== null && $trailing !== null) {
  588. if (strpos($leading, "\n") === false) {
  589. return '';
  590. }
  591. return $this->_stringHasR($leading, $trailing) ? "\r\n" : "\n";
  592. }
  593. return $leading . $trailing;
  594. }
  595. /**
  596. * Return the requested tag unescaped.
  597. *
  598. * @access protected
  599. * @param string $tag_name
  600. * @param string $leading Whitespace
  601. * @param string $trailing Whitespace
  602. * @return string
  603. */
  604. protected function _renderUnescaped($tag_name, $leading, $trailing) {
  605. $val = $this->_getVariable($tag_name);
  606. if ($this->_varIsCallable($val)) {
  607. $val = $this->_renderTemplate(call_user_func($val));
  608. }
  609. return $leading . $val . $trailing;
  610. }
  611. /**
  612. * Render the requested partial.
  613. *
  614. * @access protected
  615. * @param string $tag_name
  616. * @param string $leading Whitespace
  617. * @param string $trailing Whitespace
  618. * @return string
  619. */
  620. protected function _renderPartial($tag_name, $leading, $trailing) {
  621. $partial = $this->_getPartial($tag_name);
  622. if ($leading !== null && $trailing !== null) {
  623. $whitespace = trim($leading, "\r\n");
  624. $partial = preg_replace('/(\\r?\\n)(?!$)/s', "\\1" . $whitespace, $partial);
  625. }
  626. $view = clone($this);
  627. if ($leading !== null && $trailing !== null) {
  628. return $leading . $view->render($partial);
  629. } else {
  630. return $leading . $view->render($partial) . $trailing;
  631. }
  632. }
  633. /**
  634. * Change the Mustache tag delimiter. This method also replaces this object's current
  635. * tag RegEx with one using the new delimiters.
  636. *
  637. * @access protected
  638. * @param string $tag_name
  639. * @param string $leading Whitespace
  640. * @param string $trailing Whitespace
  641. * @return string
  642. */
  643. protected function _changeDelimiter($tag_name, $leading, $trailing) {
  644. list($otag, $ctag) = explode(' ', $tag_name);
  645. $this->_otag = $otag;
  646. $this->_ctag = $ctag;
  647. $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag);
  648. if ($leading !== null && $trailing !== null) {
  649. if (strpos($leading, "\n") === false) {
  650. return '';
  651. }
  652. return $this->_stringHasR($leading, $trailing) ? "\r\n" : "\n";
  653. }
  654. return $leading . $trailing;
  655. }
  656. /**
  657. * Push a local context onto the stack.
  658. *
  659. * @access protected
  660. * @param array &$local_context
  661. * @return void
  662. */
  663. protected function _pushContext(&$local_context) {
  664. $new = array();
  665. $new[] =& $local_context;
  666. foreach (array_keys($this->_context) as $key) {
  667. $new[] =& $this->_context[$key];
  668. }
  669. $this->_context = $new;
  670. }
  671. /**
  672. * Remove the latest context from the stack.
  673. *
  674. * @access protected
  675. * @return void
  676. */
  677. protected function _popContext() {
  678. $new = array();
  679. $keys = array_keys($this->_context);
  680. array_shift($keys);
  681. foreach ($keys as $key) {
  682. $new[] =& $this->_context[$key];
  683. }
  684. $this->_context = $new;
  685. }
  686. /**
  687. * Get a variable from the context array.
  688. *
  689. * If the view is an array, returns the value with array key $tag_name.
  690. * If the view is an object, this will check for a public member variable
  691. * named $tag_name. If none is available, this method will execute and return
  692. * any class method named $tag_name. Failing all of the above, this method will
  693. * return an empty string.
  694. *
  695. * @access protected
  696. * @param string $tag_name
  697. * @throws MustacheException Unknown variable name.
  698. * @return string
  699. */
  700. protected function _getVariable($tag_name) {
  701. if ($tag_name === '.') {
  702. return $this->_context[0];
  703. } else if (strpos($tag_name, '.') !== false) {
  704. $chunks = explode('.', $tag_name);
  705. $first = array_shift($chunks);
  706. $ret = $this->_findVariableInContext($first, $this->_context);
  707. foreach ($chunks as $next) {
  708. // Slice off a chunk of context for dot notation traversal.
  709. $c = array($ret);
  710. $ret = $this->_findVariableInContext($next, $c);
  711. }
  712. return $ret;
  713. } else {
  714. return $this->_findVariableInContext($tag_name, $this->_context);
  715. }
  716. }
  717. /**
  718. * Get a variable from the context array. Internal helper used by getVariable() to abstract
  719. * variable traversal for dot notation.
  720. *
  721. * @access protected
  722. * @param string $tag_name
  723. * @param array $context
  724. * @throws MustacheException Unknown variable name.
  725. * @return string
  726. */
  727. protected function _findVariableInContext($tag_name, $context) {
  728. foreach ($context as $view) {
  729. if (is_object($view)) {
  730. if (method_exists($view, $tag_name)) {
  731. return $view->$tag_name();
  732. } else if (isset($view->$tag_name)) {
  733. return $view->$tag_name;
  734. }
  735. } else if (is_array($view) && array_key_exists($tag_name, $view)) {
  736. return $view[$tag_name];
  737. }
  738. }
  739. if ($this->_throwsException(MustacheException::UNKNOWN_VARIABLE)) {
  740. throw new MustacheException("Unknown variable: " . $tag_name, MustacheException::UNKNOWN_VARIABLE);
  741. } else {
  742. return '';
  743. }
  744. }
  745. /**
  746. * Retrieve the partial corresponding to the requested tag name.
  747. *
  748. * Silently fails (i.e. returns '') when the requested partial is not found.
  749. *
  750. * @access protected
  751. * @param string $tag_name
  752. * @throws MustacheException Unknown partial name.
  753. * @return string
  754. */
  755. protected function _getPartial($tag_name) {
  756. if ((is_array($this->_partials) || $this->_partials instanceof ArrayAccess) && isset($this->_partials[$tag_name])) {
  757. return $this->_partials[$tag_name];
  758. }
  759. if ($this->_throwsException(MustacheException::UNKNOWN_PARTIAL)) {
  760. throw new MustacheException('Unknown partial: ' . $tag_name, MustacheException::UNKNOWN_PARTIAL);
  761. } else {
  762. return '';
  763. }
  764. }
  765. /**
  766. * Check whether the given $var should be iterated (i.e. in a section context).
  767. *
  768. * @access protected
  769. * @param mixed $var
  770. * @return bool
  771. */
  772. protected function _varIsIterable($var) {
  773. return $var instanceof Traversable || (is_array($var) && !array_diff_key($var, array_keys(array_keys($var))));
  774. }
  775. /**
  776. * Higher order sections helper: tests whether the section $var is a valid callback.
  777. *
  778. * In Mustache.php, a variable is considered 'callable' if the variable is:
  779. *
  780. * 1. an anonymous function.
  781. * 2. an object and the name of a public function, i.e. `array($SomeObject, 'methodName')`
  782. * 3. a class name and the name of a public static function, i.e. `array('SomeClass', 'methodName')`
  783. *
  784. * @access protected
  785. * @param mixed $var
  786. * @return bool
  787. */
  788. protected function _varIsCallable($var) {
  789. return !is_string($var) && is_callable($var);
  790. }
  791. }
  792. /**
  793. * MustacheException class.
  794. *
  795. * @extends Exception
  796. */
  797. class MustacheException extends Exception {
  798. // An UNKNOWN_VARIABLE exception is thrown when a {{variable}} is not found
  799. // in the current context.
  800. const UNKNOWN_VARIABLE = 0;
  801. // An UNCLOSED_SECTION exception is thrown when a {{#section}} is not closed.
  802. const UNCLOSED_SECTION = 1;
  803. // An UNEXPECTED_CLOSE_SECTION exception is thrown when {{/section}} appears
  804. // without a corresponding {{#section}} or {{^section}}.
  805. const UNEXPECTED_CLOSE_SECTION = 2;
  806. // An UNKNOWN_PARTIAL exception is thrown whenever a {{>partial}} tag appears
  807. // with no associated partial.
  808. const UNKNOWN_PARTIAL = 3;
  809. // An UNKNOWN_PRAGMA exception is thrown whenever a {{%PRAGMA}} tag appears
  810. // which can't be handled by this Mustache instance.
  811. const UNKNOWN_PRAGMA = 4;
  812. }