Mustache.php 23 KB

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