Mustache.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  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. *
  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 => $pragma_value) {
  120. if (!in_array($pragma_name, $this->_pragmasImplemented, true)) {
  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. // higher order sections
  214. if ($this->_varIsCallable($val)) {
  215. $rendered_content = $this->_renderTemplate(call_user_func($val, $content));
  216. } else if ($this->_varIsIterable($val)) {
  217. foreach ($val as $local_context) {
  218. $this->_pushContext($local_context);
  219. $rendered_content .= $this->_renderTemplate($content);
  220. $this->_popContext();
  221. }
  222. } else if ($val) {
  223. if (is_array($val) || is_object($val)) {
  224. $this->_pushContext($val);
  225. $rendered_content = $this->_renderTemplate($content);
  226. $this->_popContext();
  227. } else {
  228. $rendered_content = $this->_renderTemplate($content);
  229. }
  230. }
  231. break;
  232. }
  233. return $rendered_before . $rendered_content . $this->_renderTemplate($after);
  234. }
  235. return $this->_renderTags($template);
  236. }
  237. /**
  238. * Prepare a section RegEx string for the given opening/closing tags.
  239. *
  240. * @access protected
  241. * @param string $otag
  242. * @param string $ctag
  243. * @return string
  244. */
  245. protected function _prepareSectionRegEx($otag, $ctag) {
  246. return sprintf(
  247. '/(?:(?<=\\n)[ \\t]*)?%s(?:(?P<type>[%s])(?P<tag_name>.+?)|=(?P<delims>.*?)=)%s\\n?/s',
  248. preg_quote($otag, '/'),
  249. self::SECTION_TYPES,
  250. preg_quote($ctag, '/')
  251. );
  252. }
  253. /**
  254. * Extract the first section from $template.
  255. *
  256. * @access protected
  257. * @param string $template
  258. * @return array $before, $type, $tag_name, $content and $after
  259. */
  260. protected function _findSection($template) {
  261. $regEx = $this->_prepareSectionRegEx($this->_otag, $this->_ctag);
  262. $section_start = null;
  263. $section_type = null;
  264. $content_start = null;
  265. $search_offset = 0;
  266. $section_stack = array();
  267. $matches = array();
  268. while (preg_match($regEx, $template, $matches, PREG_OFFSET_CAPTURE, $search_offset)) {
  269. if (isset($matches['delims'][0])) {
  270. list($otag, $ctag) = explode(' ', $matches['delims'][0]);
  271. $regEx = $this->_prepareSectionRegEx($otag, $ctag);
  272. $search_offset = $matches[0][1] + strlen($matches[0][0]);
  273. continue;
  274. }
  275. $match = $matches[0][0];
  276. $offset = $matches[0][1];
  277. $type = $matches['type'][0];
  278. $tag_name = trim($matches['tag_name'][0]);
  279. $search_offset = $offset + strlen($match);
  280. switch ($type) {
  281. case '^':
  282. case '#':
  283. if (empty($section_stack)) {
  284. $section_start = $offset;
  285. $section_type = $type;
  286. $content_start = $search_offset;
  287. }
  288. array_push($section_stack, $tag_name);
  289. break;
  290. case '/':
  291. if (empty($section_stack) || ($tag_name !== array_pop($section_stack))) {
  292. if ($this->_throwsException(MustacheException::UNEXPECTED_CLOSE_SECTION)) {
  293. throw new MustacheException('Unexpected close section: ' . $tag_name, MustacheException::UNEXPECTED_CLOSE_SECTION);
  294. }
  295. }
  296. if (empty($section_stack)) {
  297. // $before, $type, $tag_name, $content, $after
  298. return array(
  299. substr($template, 0, $section_start),
  300. $section_type,
  301. $tag_name,
  302. substr($template, $content_start, $offset - $content_start),
  303. substr($template, $search_offset),
  304. );
  305. }
  306. break;
  307. }
  308. }
  309. if (!empty($section_stack)) {
  310. if ($this->_throwsException(MustacheException::UNCLOSED_SECTION)) {
  311. throw new MustacheException('Unclosed section: ' . $section_stack[0], MustacheException::UNCLOSED_SECTION);
  312. }
  313. }
  314. }
  315. /**
  316. * Prepare a pragma RegEx for the given opening/closing tags.
  317. *
  318. * @access protected
  319. * @param string $otag
  320. * @param string $ctag
  321. * @return string
  322. */
  323. protected function _preparePragmaRegEx($otag, $ctag) {
  324. return sprintf(
  325. '/%s%%\\s*(?P<pragma_name>[\\w_-]+)(?P<options_string>(?: [\\w]+=[\\w]+)*)\\s*%s\\n?/s',
  326. preg_quote($otag, '/'),
  327. preg_quote($ctag, '/')
  328. );
  329. }
  330. /**
  331. * Initialize pragmas and remove all pragma tags.
  332. *
  333. * @access protected
  334. * @param string $template
  335. * @return string
  336. */
  337. protected function _renderPragmas($template) {
  338. $this->_localPragmas = $this->_pragmas;
  339. // no pragmas
  340. if (strpos($template, $this->_otag . '%') === false) {
  341. return $template;
  342. }
  343. $regEx = $this->_preparePragmaRegEx($this->_otag, $this->_ctag);
  344. return preg_replace_callback($regEx, array($this, '_renderPragma'), $template);
  345. }
  346. /**
  347. * A preg_replace helper to remove {{%PRAGMA}} tags and enable requested pragma.
  348. *
  349. * @access protected
  350. * @param mixed $matches
  351. * @return void
  352. * @throws MustacheException unknown pragma
  353. */
  354. protected function _renderPragma($matches) {
  355. $pragma = $matches[0];
  356. $pragma_name = $matches['pragma_name'];
  357. $options_string = $matches['options_string'];
  358. if (!in_array($pragma_name, $this->_pragmasImplemented)) {
  359. if($this->_throwsException(MustacheException::UNKNOWN_PRAGMA))
  360. throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
  361. else
  362. return '';
  363. }
  364. $options = array();
  365. foreach (explode(' ', trim($options_string)) as $o) {
  366. if ($p = trim($o)) {
  367. $p = explode('=', $p);
  368. $options[$p[0]] = $p[1];
  369. }
  370. }
  371. if (empty($options)) {
  372. $this->_localPragmas[$pragma_name] = true;
  373. } else {
  374. $this->_localPragmas[$pragma_name] = $options;
  375. }
  376. return '';
  377. }
  378. /**
  379. * Check whether this Mustache has a specific pragma.
  380. *
  381. * @access protected
  382. * @param string $pragma_name
  383. * @return bool
  384. */
  385. protected function _hasPragma($pragma_name) {
  386. if (array_key_exists($pragma_name, $this->_localPragmas) && $this->_localPragmas[$pragma_name]) {
  387. return true;
  388. } else {
  389. return false;
  390. }
  391. }
  392. /**
  393. * Return pragma options, if any.
  394. *
  395. * @access protected
  396. * @param string $pragma_name
  397. * @return mixed
  398. * @throws MustacheException Unknown pragma
  399. */
  400. protected function _getPragmaOptions($pragma_name) {
  401. if (!$this->_hasPragma($pragma_name)) {
  402. if($this->_throwsException(MustacheException::UNKNOWN_PRAGMA))
  403. throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
  404. else
  405. return array();
  406. }
  407. return (is_array($this->_localPragmas[$pragma_name])) ? $this->_localPragmas[$pragma_name] : array();
  408. }
  409. /**
  410. * Check whether this Mustache instance throws a given exception.
  411. *
  412. * Expects exceptions to be MustacheException error codes (i.e. class constants).
  413. *
  414. * @access protected
  415. * @param mixed $exception
  416. * @return void
  417. */
  418. protected function _throwsException($exception) {
  419. return (isset($this->_throwsExceptions[$exception]) && $this->_throwsExceptions[$exception]);
  420. }
  421. /**
  422. * Prepare a tag RegEx for the given opening/closing tags.
  423. *
  424. * @access protected
  425. * @param string $otag
  426. * @param string $ctag
  427. * @return string
  428. */
  429. protected function _prepareTagRegEx($otag, $ctag, $first = false) {
  430. return sprintf(
  431. '/(?P<leading>(?:%s\\r?\\n)[ \\t]*)?%s(?P<type>[%s]?)(?P<tag_name>.+?)(?:\\2|})?%s(?P<trailing>\\s*(?:\\r?\\n|\\Z))?/s',
  432. ($first ? '\\A|' : ''),
  433. preg_quote($otag, '/'),
  434. self::TAG_TYPES,
  435. preg_quote($ctag, '/')
  436. );
  437. }
  438. /**
  439. * Loop through and render individual Mustache tags.
  440. *
  441. * @access protected
  442. * @param string $template
  443. * @return void
  444. */
  445. protected function _renderTags($template) {
  446. if (strpos($template, $this->_otag) === false) {
  447. return $template;
  448. }
  449. $first = true;
  450. $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag, true);
  451. $html = '';
  452. $matches = array();
  453. while (preg_match($this->_tagRegEx, $template, $matches, PREG_OFFSET_CAPTURE)) {
  454. $tag = $matches[0][0];
  455. $offset = $matches[0][1];
  456. $modifier = $matches['type'][0];
  457. $tag_name = trim($matches['tag_name'][0]);
  458. if (isset($matches['leading']) && $matches['leading'][1] > -1) {
  459. $leading = $matches['leading'][0];
  460. } else {
  461. $leading = null;
  462. }
  463. if (isset($matches['trailing']) && $matches['trailing'][1] > -1) {
  464. $trailing = $matches['trailing'][0];
  465. } else {
  466. $trailing = null;
  467. }
  468. $html .= substr($template, 0, $offset);
  469. $next_offset = $offset + strlen($tag);
  470. if ((substr($html, -1) == "\n") && (substr($template, $next_offset, 1) == "\n")) {
  471. $next_offset++;
  472. }
  473. $template = substr($template, $next_offset);
  474. $html .= $this->_renderTag($modifier, $tag_name, $leading, $trailing);
  475. if ($first == true) {
  476. $first = false;
  477. $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag);
  478. }
  479. }
  480. return $html . $template;
  481. }
  482. /**
  483. * Render the named tag, given the specified modifier.
  484. *
  485. * Accepted modifiers are `=` (change delimiter), `!` (comment), `>` (partial)
  486. * `{` or `&` (don't escape output), or none (render escaped output).
  487. *
  488. * @access protected
  489. * @param string $modifier
  490. * @param string $tag_name
  491. * @param string $leading Whitespace
  492. * @param string $trailing Whitespace
  493. * @throws MustacheException Unmatched section tag encountered.
  494. * @return string
  495. */
  496. protected function _renderTag($modifier, $tag_name, $leading, $trailing) {
  497. switch ($modifier) {
  498. case '=':
  499. return $this->_changeDelimiter($tag_name, $leading, $trailing);
  500. break;
  501. case '!':
  502. return $this->_renderComment($tag_name, $leading, $trailing);
  503. break;
  504. case '>':
  505. case '<':
  506. return $this->_renderPartial($tag_name, $leading, $trailing);
  507. break;
  508. case '{':
  509. // strip the trailing } ...
  510. if ($tag_name[(strlen($tag_name) - 1)] == '}') {
  511. $tag_name = substr($tag_name, 0, -1);
  512. }
  513. case '&':
  514. if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) {
  515. return $this->_renderEscaped($tag_name, $leading, $trailing);
  516. } else {
  517. return $this->_renderUnescaped($tag_name, $leading, $trailing);
  518. }
  519. break;
  520. case '#':
  521. case '^':
  522. case '/':
  523. // remove any leftover section tags
  524. return $leading . $trailing;
  525. break;
  526. default:
  527. if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) {
  528. return $this->_renderUnescaped($modifier . $tag_name, $leading, $trailing);
  529. } else {
  530. return $this->_renderEscaped($modifier . $tag_name, $leading, $trailing);
  531. }
  532. break;
  533. }
  534. }
  535. /**
  536. * Returns true if any of its args contains the "\r" character.
  537. *
  538. * @access protected
  539. * @param string $str
  540. * @return boolean
  541. */
  542. protected function _stringHasR($str) {
  543. foreach (func_get_args() as $arg) {
  544. if (strpos($arg, "\r") !== false) {
  545. return true;
  546. }
  547. }
  548. return false;
  549. }
  550. /**
  551. * Escape and return the requested tag.
  552. *
  553. * @access protected
  554. * @param string $tag_name
  555. * @param string $leading Whitespace
  556. * @param string $trailing Whitespace
  557. * @return string
  558. */
  559. protected function _renderEscaped($tag_name, $leading, $trailing) {
  560. $rendered = htmlentities($this->_renderUnescaped($tag_name, '', ''), ENT_COMPAT, $this->_charset);
  561. return $leading . $rendered . $trailing;
  562. }
  563. /**
  564. * Render a comment (i.e. return an empty string).
  565. *
  566. * @access protected
  567. * @param string $tag_name
  568. * @param string $leading Whitespace
  569. * @param string $trailing Whitespace
  570. * @return string
  571. */
  572. protected function _renderComment($tag_name, $leading, $trailing) {
  573. if ($leading !== null && $trailing !== null) {
  574. if (strpos($leading, "\n") === false) {
  575. return '';
  576. }
  577. return $this->_stringHasR($leading, $trailing) ? "\r\n" : "\n";
  578. }
  579. return $leading . $trailing;
  580. }
  581. /**
  582. * Return the requested tag unescaped.
  583. *
  584. * @access protected
  585. * @param string $tag_name
  586. * @param string $leading Whitespace
  587. * @param string $trailing Whitespace
  588. * @return string
  589. */
  590. protected function _renderUnescaped($tag_name, $leading, $trailing) {
  591. $val = $this->_getVariable($tag_name);
  592. if ($this->_varIsCallable($val)) {
  593. $val = $this->_renderTemplate(call_user_func($val));
  594. }
  595. return $leading . $val . $trailing;
  596. }
  597. /**
  598. * Render the requested partial.
  599. *
  600. * @access protected
  601. * @param string $tag_name
  602. * @param string $leading Whitespace
  603. * @param string $trailing Whitespace
  604. * @return string
  605. */
  606. protected function _renderPartial($tag_name, $leading, $trailing) {
  607. $partial = $this->_getPartial($tag_name);
  608. if ($leading !== null && $trailing !== null) {
  609. $whitespace = trim($leading, "\r\n");
  610. $partial = preg_replace('/(\\r?\\n)(?!$)/s', "\\1" . $whitespace, $partial);
  611. }
  612. $view = clone($this);
  613. if ($leading !== null && $trailing !== null) {
  614. return $leading . $view->render($partial);
  615. } else {
  616. return $leading . $view->render($partial) . $trailing;
  617. }
  618. }
  619. /**
  620. * Change the Mustache tag delimiter. This method also replaces this object's current
  621. * tag RegEx with one using the new delimiters.
  622. *
  623. * @access protected
  624. * @param string $tag_name
  625. * @param string $leading Whitespace
  626. * @param string $trailing Whitespace
  627. * @return string
  628. */
  629. protected function _changeDelimiter($tag_name, $leading, $trailing) {
  630. list($otag, $ctag) = explode(' ', $tag_name);
  631. $this->_otag = $otag;
  632. $this->_ctag = $ctag;
  633. $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag);
  634. if ($leading !== null && $trailing !== null) {
  635. if (strpos($leading, "\n") === false) {
  636. return '';
  637. }
  638. return $this->_stringHasR($leading, $trailing) ? "\r\n" : "\n";
  639. }
  640. return $leading . $trailing;
  641. }
  642. /**
  643. * Push a local context onto the stack.
  644. *
  645. * @access protected
  646. * @param array &$local_context
  647. * @return void
  648. */
  649. protected function _pushContext(&$local_context) {
  650. $new = array();
  651. $new[] =& $local_context;
  652. foreach (array_keys($this->_context) as $key) {
  653. $new[] =& $this->_context[$key];
  654. }
  655. $this->_context = $new;
  656. }
  657. /**
  658. * Remove the latest context from the stack.
  659. *
  660. * @access protected
  661. * @return void
  662. */
  663. protected function _popContext() {
  664. $new = array();
  665. $keys = array_keys($this->_context);
  666. array_shift($keys);
  667. foreach ($keys as $key) {
  668. $new[] =& $this->_context[$key];
  669. }
  670. $this->_context = $new;
  671. }
  672. /**
  673. * Get a variable from the context array.
  674. *
  675. * If the view is an array, returns the value with array key $tag_name.
  676. * If the view is an object, this will check for a public member variable
  677. * named $tag_name. If none is available, this method will execute and return
  678. * any class method named $tag_name. Failing all of the above, this method will
  679. * return an empty string.
  680. *
  681. * @access protected
  682. * @param string $tag_name
  683. * @throws MustacheException Unknown variable name.
  684. * @return string
  685. */
  686. protected function _getVariable($tag_name) {
  687. if ($tag_name === '.') {
  688. return $this->_context[0];
  689. } else if (strpos($tag_name, '.') !== false) {
  690. $chunks = explode('.', $tag_name);
  691. $first = array_shift($chunks);
  692. $ret = $this->_findVariableInContext($first, $this->_context);
  693. while ($next = array_shift($chunks)) {
  694. // Slice off a chunk of context for dot notation traversal.
  695. $c = array($ret);
  696. $ret = $this->_findVariableInContext($next, $c);
  697. }
  698. return $ret;
  699. } else {
  700. return $this->_findVariableInContext($tag_name, $this->_context);
  701. }
  702. }
  703. /**
  704. * Get a variable from the context array. Internal helper used by getVariable() to abstract
  705. * variable traversal for dot notation.
  706. *
  707. * @access protected
  708. * @param string $tag_name
  709. * @param array $context
  710. * @throws MustacheException Unknown variable name.
  711. * @return string
  712. */
  713. protected function _findVariableInContext($tag_name, $context) {
  714. foreach ($context as $view) {
  715. if (is_object($view)) {
  716. if (method_exists($view, $tag_name)) {
  717. return $view->$tag_name();
  718. } else if (isset($view->$tag_name)) {
  719. return $view->$tag_name;
  720. }
  721. } else if (is_array($view) && array_key_exists($tag_name, $view)) {
  722. return $view[$tag_name];
  723. }
  724. }
  725. if ($this->_throwsException(MustacheException::UNKNOWN_VARIABLE)) {
  726. throw new MustacheException("Unknown variable: " . $tag_name, MustacheException::UNKNOWN_VARIABLE);
  727. } else {
  728. return '';
  729. }
  730. }
  731. /**
  732. * Retrieve the partial corresponding to the requested tag name.
  733. *
  734. * Silently fails (i.e. returns '') when the requested partial is not found.
  735. *
  736. * @access protected
  737. * @param string $tag_name
  738. * @throws MustacheException Unknown partial name.
  739. * @return string
  740. */
  741. protected function _getPartial($tag_name) {
  742. if ((is_array($this->_partials) || $this->_partials instanceof ArrayAccess) && isset($this->_partials[$tag_name])) {
  743. return $this->_partials[$tag_name];
  744. }
  745. if ($this->_throwsException(MustacheException::UNKNOWN_PARTIAL)) {
  746. throw new MustacheException('Unknown partial: ' . $tag_name, MustacheException::UNKNOWN_PARTIAL);
  747. } else {
  748. return '';
  749. }
  750. }
  751. /**
  752. * Check whether the given $var should be iterated (i.e. in a section context).
  753. *
  754. * @access protected
  755. * @param mixed $var
  756. * @return bool
  757. */
  758. protected function _varIsIterable($var) {
  759. return $var instanceof Traversable || (is_array($var) && !array_diff_key($var, array_keys(array_keys($var))));
  760. }
  761. /**
  762. * Higher order sections helper: tests whether the section $var is a valid callback.
  763. *
  764. * In Mustache.php, a variable is considered 'callable' if the variable is:
  765. *
  766. * 1. an anonymous function.
  767. * 2. an object and the name of a public function, i.e. `array($SomeObject, 'methodName')`
  768. * 3. a class name and the name of a public static function, i.e. `array('SomeClass', 'methodName')`
  769. *
  770. * @access protected
  771. * @param mixed $var
  772. * @return bool
  773. */
  774. protected function _varIsCallable($var) {
  775. return !is_string($var) && is_callable($var);
  776. }
  777. }
  778. /**
  779. * MustacheException class.
  780. *
  781. * @extends Exception
  782. */
  783. class MustacheException extends Exception {
  784. // An UNKNOWN_VARIABLE exception is thrown when a {{variable}} is not found
  785. // in the current context.
  786. const UNKNOWN_VARIABLE = 0;
  787. // An UNCLOSED_SECTION exception is thrown when a {{#section}} is not closed.
  788. const UNCLOSED_SECTION = 1;
  789. // An UNEXPECTED_CLOSE_SECTION exception is thrown when {{/section}} appears
  790. // without a corresponding {{#section}} or {{^section}}.
  791. const UNEXPECTED_CLOSE_SECTION = 2;
  792. // An UNKNOWN_PARTIAL exception is thrown whenever a {{>partial}} tag appears
  793. // with no associated partial.
  794. const UNKNOWN_PARTIAL = 3;
  795. // An UNKNOWN_PRAGMA exception is thrown whenever a {{%PRAGMA}} tag appears
  796. // which can't be handled by this Mustache instance.
  797. const UNKNOWN_PRAGMA = 4;
  798. }