Mustache.php 23 KB

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