Mustache.php 22 KB

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