PageRenderTime 64ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/www/protected/vendors/mustache.php/Mustache.php

https://bitbucket.org/badenkov/demo
PHP | 889 lines | 450 code | 97 blank | 342 comment | 102 complexity | 7b3e986f173470a50322e57cd4c62d2a MD5 | raw file
Possible License(s): Apache-2.0, MIT, LGPL-2.1, BSD-2-Clause, CC-BY-SA-3.0, BSD-3-Clause
  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. throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
  360. }
  361. $options = array();
  362. foreach (explode(' ', trim($options_string)) as $o) {
  363. if ($p = trim($o)) {
  364. $p = explode('=', $p);
  365. $options[$p[0]] = $p[1];
  366. }
  367. }
  368. if (empty($options)) {
  369. $this->_localPragmas[$pragma_name] = true;
  370. } else {
  371. $this->_localPragmas[$pragma_name] = $options;
  372. }
  373. return '';
  374. }
  375. /**
  376. * Check whether this Mustache has a specific pragma.
  377. *
  378. * @access protected
  379. * @param string $pragma_name
  380. * @return bool
  381. */
  382. protected function _hasPragma($pragma_name) {
  383. if (array_key_exists($pragma_name, $this->_localPragmas) && $this->_localPragmas[$pragma_name]) {
  384. return true;
  385. } else {
  386. return false;
  387. }
  388. }
  389. /**
  390. * Return pragma options, if any.
  391. *
  392. * @access protected
  393. * @param string $pragma_name
  394. * @return mixed
  395. * @throws MustacheException Unknown pragma
  396. */
  397. protected function _getPragmaOptions($pragma_name) {
  398. if (!$this->_hasPragma($pragma_name)) {
  399. throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
  400. }
  401. return (is_array($this->_localPragmas[$pragma_name])) ? $this->_localPragmas[$pragma_name] : array();
  402. }
  403. /**
  404. * Check whether this Mustache instance throws a given exception.
  405. *
  406. * Expects exceptions to be MustacheException error codes (i.e. class constants).
  407. *
  408. * @access protected
  409. * @param mixed $exception
  410. * @return void
  411. */
  412. protected function _throwsException($exception) {
  413. return (isset($this->_throwsExceptions[$exception]) && $this->_throwsExceptions[$exception]);
  414. }
  415. /**
  416. * Prepare a tag RegEx for the given opening/closing tags.
  417. *
  418. * @access protected
  419. * @param string $otag
  420. * @param string $ctag
  421. * @return string
  422. */
  423. protected function _prepareTagRegEx($otag, $ctag, $first = false) {
  424. return sprintf(
  425. '/(?P<leading>(?:%s\\r?\\n)[ \\t]*)?%s(?P<type>[%s]?)(?P<tag_name>.+?)(?:\\2|})?%s(?P<trailing>\\s*(?:\\r?\\n|\\Z))?/s',
  426. ($first ? '\\A|' : ''),
  427. preg_quote($otag, '/'),
  428. self::TAG_TYPES,
  429. preg_quote($ctag, '/')
  430. );
  431. }
  432. /**
  433. * Loop through and render individual Mustache tags.
  434. *
  435. * @access protected
  436. * @param string $template
  437. * @return void
  438. */
  439. protected function _renderTags($template) {
  440. if (strpos($template, $this->_otag) === false) {
  441. return $template;
  442. }
  443. $first = true;
  444. $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag, true);
  445. $html = '';
  446. $matches = array();
  447. while (preg_match($this->_tagRegEx, $template, $matches, PREG_OFFSET_CAPTURE)) {
  448. $tag = $matches[0][0];
  449. $offset = $matches[0][1];
  450. $modifier = $matches['type'][0];
  451. $tag_name = trim($matches['tag_name'][0]);
  452. if (isset($matches['leading']) && $matches['leading'][1] > -1) {
  453. $leading = $matches['leading'][0];
  454. } else {
  455. $leading = null;
  456. }
  457. if (isset($matches['trailing']) && $matches['trailing'][1] > -1) {
  458. $trailing = $matches['trailing'][0];
  459. } else {
  460. $trailing = null;
  461. }
  462. $html .= substr($template, 0, $offset);
  463. $next_offset = $offset + strlen($tag);
  464. if ((substr($html, -1) == "\n") && (substr($template, $next_offset, 1) == "\n")) {
  465. $next_offset++;
  466. }
  467. $template = substr($template, $next_offset);
  468. $html .= $this->_renderTag($modifier, $tag_name, $leading, $trailing);
  469. if ($first == true) {
  470. $first = false;
  471. $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag);
  472. }
  473. }
  474. return $html . $template;
  475. }
  476. /**
  477. * Render the named tag, given the specified modifier.
  478. *
  479. * Accepted modifiers are `=` (change delimiter), `!` (comment), `>` (partial)
  480. * `{` or `&` (don't escape output), or none (render escaped output).
  481. *
  482. * @access protected
  483. * @param string $modifier
  484. * @param string $tag_name
  485. * @param string $leading Whitespace
  486. * @param string $trailing Whitespace
  487. * @throws MustacheException Unmatched section tag encountered.
  488. * @return string
  489. */
  490. protected function _renderTag($modifier, $tag_name, $leading, $trailing) {
  491. switch ($modifier) {
  492. case '=':
  493. return $this->_changeDelimiter($tag_name, $leading, $trailing);
  494. break;
  495. case '!':
  496. return $this->_renderComment($tag_name, $leading, $trailing);
  497. break;
  498. case '>':
  499. case '<':
  500. return $this->_renderPartial($tag_name, $leading, $trailing);
  501. break;
  502. case '{':
  503. // strip the trailing } ...
  504. if ($tag_name[(strlen($tag_name) - 1)] == '}') {
  505. $tag_name = substr($tag_name, 0, -1);
  506. }
  507. case '&':
  508. if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) {
  509. return $this->_renderEscaped($tag_name, $leading, $trailing);
  510. } else {
  511. return $this->_renderUnescaped($tag_name, $leading, $trailing);
  512. }
  513. break;
  514. case '#':
  515. case '^':
  516. case '/':
  517. // remove any leftover section tags
  518. return $leading . $trailing;
  519. break;
  520. default:
  521. if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) {
  522. return $this->_renderUnescaped($modifier . $tag_name, $leading, $trailing);
  523. } else {
  524. return $this->_renderEscaped($modifier . $tag_name, $leading, $trailing);
  525. }
  526. break;
  527. }
  528. }
  529. /**
  530. * Returns true if any of its args contains the "\r" character.
  531. *
  532. * @access protected
  533. * @param string $str
  534. * @return boolean
  535. */
  536. protected function _stringHasR($str) {
  537. foreach (func_get_args() as $arg) {
  538. if (strpos($arg, "\r") !== false) {
  539. return true;
  540. }
  541. }
  542. return false;
  543. }
  544. /**
  545. * Escape and return the requested tag.
  546. *
  547. * @access protected
  548. * @param string $tag_name
  549. * @param string $leading Whitespace
  550. * @param string $trailing Whitespace
  551. * @return string
  552. */
  553. protected function _renderEscaped($tag_name, $leading, $trailing) {
  554. $rendered = htmlentities($this->_renderUnescaped($tag_name, '', ''), ENT_COMPAT, $this->_charset);
  555. return $leading . $rendered . $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. $val = $this->_getVariable($tag_name);
  586. if ($this->_varIsCallable($val)) {
  587. $val = $this->_renderTemplate(call_user_func($val));
  588. }
  589. return $leading . $val . $trailing;
  590. }
  591. /**
  592. * Render the requested partial.
  593. *
  594. * @access protected
  595. * @param string $tag_name
  596. * @param string $leading Whitespace
  597. * @param string $trailing Whitespace
  598. * @return string
  599. */
  600. protected function _renderPartial($tag_name, $leading, $trailing) {
  601. $partial = $this->_getPartial($tag_name);
  602. if ($leading !== null && $trailing !== null) {
  603. $whitespace = trim($leading, "\r\n");
  604. $partial = preg_replace('/(\\r?\\n)(?!$)/s', "\\1" . $whitespace, $partial);
  605. }
  606. $view = clone($this);
  607. if ($leading !== null && $trailing !== null) {
  608. return $leading . $view->render($partial);
  609. } else {
  610. return $leading . $view->render($partial) . $trailing;
  611. }
  612. }
  613. /**
  614. * Change the Mustache tag delimiter. This method also replaces this object's current
  615. * tag RegEx with one using the new delimiters.
  616. *
  617. * @access protected
  618. * @param string $tag_name
  619. * @param string $leading Whitespace
  620. * @param string $trailing Whitespace
  621. * @return string
  622. */
  623. protected function _changeDelimiter($tag_name, $leading, $trailing) {
  624. list($otag, $ctag) = explode(' ', $tag_name);
  625. $this->_otag = $otag;
  626. $this->_ctag = $ctag;
  627. $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag);
  628. if ($leading !== null && $trailing !== null) {
  629. if (strpos($leading, "\n") === false) {
  630. return '';
  631. }
  632. return $this->_stringHasR($leading, $trailing) ? "\r\n" : "\n";
  633. }
  634. return $leading . $trailing;
  635. }
  636. /**
  637. * Push a local context onto the stack.
  638. *
  639. * @access protected
  640. * @param array &$local_context
  641. * @return void
  642. */
  643. protected function _pushContext(&$local_context) {
  644. $new = array();
  645. $new[] =& $local_context;
  646. foreach (array_keys($this->_context) as $key) {
  647. $new[] =& $this->_context[$key];
  648. }
  649. $this->_context = $new;
  650. }
  651. /**
  652. * Remove the latest context from the stack.
  653. *
  654. * @access protected
  655. * @return void
  656. */
  657. protected function _popContext() {
  658. $new = array();
  659. $keys = array_keys($this->_context);
  660. array_shift($keys);
  661. foreach ($keys as $key) {
  662. $new[] =& $this->_context[$key];
  663. }
  664. $this->_context = $new;
  665. }
  666. /**
  667. * Get a variable from the context array.
  668. *
  669. * If the view is an array, returns the value with array key $tag_name.
  670. * If the view is an object, this will check for a public member variable
  671. * named $tag_name. If none is available, this method will execute and return
  672. * any class method named $tag_name. Failing all of the above, this method will
  673. * return an empty string.
  674. *
  675. * @access protected
  676. * @param string $tag_name
  677. * @throws MustacheException Unknown variable name.
  678. * @return string
  679. */
  680. protected function _getVariable($tag_name) {
  681. if ($tag_name === '.') {
  682. return $this->_context[0];
  683. } else if (strpos($tag_name, '.') !== false) {
  684. $chunks = explode('.', $tag_name);
  685. $first = array_shift($chunks);
  686. $ret = $this->_findVariableInContext($first, $this->_context);
  687. while ($next = array_shift($chunks)) {
  688. // Slice off a chunk of context for dot notation traversal.
  689. $c = array($ret);
  690. $ret = $this->_findVariableInContext($next, $c);
  691. }
  692. return $ret;
  693. } else {
  694. return $this->_findVariableInContext($tag_name, $this->_context);
  695. }
  696. }
  697. /**
  698. * Get a variable from the context array. Internal helper used by getVariable() to abstract
  699. * variable traversal for dot notation.
  700. *
  701. * @access protected
  702. * @param string $tag_name
  703. * @param array $context
  704. * @throws MustacheException Unknown variable name.
  705. * @return string
  706. */
  707. protected function _findVariableInContext($tag_name, $context) {
  708. foreach ($context as $view) {
  709. if (is_object($view)) {
  710. if (method_exists($view, $tag_name)) {
  711. return $view->$tag_name();
  712. } else if (isset($view->$tag_name)) {
  713. return $view->$tag_name;
  714. }
  715. } else if (is_array($view) && array_key_exists($tag_name, $view)) {
  716. return $view[$tag_name];
  717. }
  718. }
  719. if ($this->_throwsException(MustacheException::UNKNOWN_VARIABLE)) {
  720. throw new MustacheException("Unknown variable: " . $tag_name, MustacheException::UNKNOWN_VARIABLE);
  721. } else {
  722. return '';
  723. }
  724. }
  725. /**
  726. * Retrieve the partial corresponding to the requested tag name.
  727. *
  728. * Silently fails (i.e. returns '') when the requested partial is not found.
  729. *
  730. * @access protected
  731. * @param string $tag_name
  732. * @throws MustacheException Unknown partial name.
  733. * @return string
  734. */
  735. protected function _getPartial($tag_name) {
  736. if ((is_array($this->_partials) || $this->_partials instanceof ArrayAccess) && isset($this->_partials[$tag_name])) {
  737. return $this->_partials[$tag_name];
  738. }
  739. if ($this->_throwsException(MustacheException::UNKNOWN_PARTIAL)) {
  740. throw new MustacheException('Unknown partial: ' . $tag_name, MustacheException::UNKNOWN_PARTIAL);
  741. } else {
  742. return '';
  743. }
  744. }
  745. /**
  746. * Check whether the given $var should be iterated (i.e. in a section context).
  747. *
  748. * @access protected
  749. * @param mixed $var
  750. * @return bool
  751. */
  752. protected function _varIsIterable($var) {
  753. return $var instanceof Traversable || (is_array($var) && !array_diff_key($var, array_keys(array_keys($var))));
  754. }
  755. /**
  756. * Higher order sections helper: tests whether the section $var is a valid callback.
  757. *
  758. * In Mustache.php, a variable is considered 'callable' if the variable is:
  759. *
  760. * 1. an anonymous function.
  761. * 2. an object and the name of a public function, i.e. `array($SomeObject, 'methodName')`
  762. * 3. a class name and the name of a public static function, i.e. `array('SomeClass', 'methodName')`
  763. *
  764. * @access protected
  765. * @param mixed $var
  766. * @return bool
  767. */
  768. protected function _varIsCallable($var) {
  769. return !is_string($var) && is_callable($var);
  770. }
  771. }
  772. /**
  773. * MustacheException class.
  774. *
  775. * @extends Exception
  776. */
  777. class MustacheException extends Exception {
  778. // An UNKNOWN_VARIABLE exception is thrown when a {{variable}} is not found
  779. // in the current context.
  780. const UNKNOWN_VARIABLE = 0;
  781. // An UNCLOSED_SECTION exception is thrown when a {{#section}} is not closed.
  782. const UNCLOSED_SECTION = 1;
  783. // An UNEXPECTED_CLOSE_SECTION exception is thrown when {{/section}} appears
  784. // without a corresponding {{#section}} or {{^section}}.
  785. const UNEXPECTED_CLOSE_SECTION = 2;
  786. // An UNKNOWN_PARTIAL exception is thrown whenever a {{>partial}} tag appears
  787. // with no associated partial.
  788. const UNKNOWN_PARTIAL = 3;
  789. // An UNKNOWN_PRAGMA exception is thrown whenever a {{%PRAGMA}} tag appears
  790. // which can't be handled by this Mustache instance.
  791. const UNKNOWN_PRAGMA = 4;
  792. }