Engine.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. <?php
  2. /*
  3. * This file is part of Mustache.php.
  4. *
  5. * (c) 2012 Justin Hileman
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. /**
  11. * A Mustache implementation in PHP.
  12. *
  13. * {@link http://defunkt.github.com/mustache}
  14. *
  15. * Mustache is a framework-agnostic logic-less templating language. It enforces separation of view
  16. * logic from template files. In fact, it is not even possible to embed logic in the template.
  17. *
  18. * This is very, very rad.
  19. *
  20. * @author Justin Hileman {@link http://justinhileman.com}
  21. */
  22. class Mustache_Engine
  23. {
  24. const VERSION = '2.0.2';
  25. const SPEC_VERSION = '1.1.2';
  26. const PRAGMA_FILTERS = 'FILTERS';
  27. // Template cache
  28. private $templates = array();
  29. // Environment
  30. private $templateClassPrefix = '__Mustache_';
  31. private $cache = null;
  32. private $cacheFileMode = null;
  33. private $loader;
  34. private $partialsLoader;
  35. private $helpers;
  36. private $escape;
  37. private $charset = 'UTF-8';
  38. private $logger;
  39. /**
  40. * Mustache class constructor.
  41. *
  42. * Passing an $options array allows overriding certain Mustache options during instantiation:
  43. *
  44. * $options = array(
  45. * // The class prefix for compiled templates. Defaults to '__Mustache_'.
  46. * 'template_class_prefix' => '__MyTemplates_',
  47. *
  48. * // A cache directory for compiled templates. Mustache will not cache templates unless this is set
  49. * 'cache' => dirname(__FILE__).'/tmp/cache/mustache',
  50. *
  51. * // Override default permissions for cache files. Defaults to using the system-defined umask. It is
  52. * // *strongly* recommended that you configure your umask properly rather than overriding permissions here.
  53. * 'cache_file_mode' => 0666,
  54. *
  55. * // A Mustache template loader instance. Uses a StringLoader if not specified.
  56. * 'loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views'),
  57. *
  58. * // A Mustache loader instance for partials.
  59. * 'partials_loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views/partials'),
  60. *
  61. * // An array of Mustache partials. Useful for quick-and-dirty string template loading, but not as
  62. * // efficient or lazy as a Filesystem (or database) loader.
  63. * 'partials' => array('foo' => file_get_contents(dirname(__FILE__).'/views/partials/foo.mustache')),
  64. *
  65. * // An array of 'helpers'. Helpers can be global variables or objects, closures (e.g. for higher order
  66. * // sections), or any other valid Mustache context value. They will be prepended to the context stack,
  67. * // so they will be available in any template loaded by this Mustache instance.
  68. * 'helpers' => array('i18n' => function($text) {
  69. * // do something translatey here...
  70. * }),
  71. *
  72. * // An 'escape' callback, responsible for escaping double-mustache variables.
  73. * 'escape' => function($value) {
  74. * return htmlspecialchars($buffer, ENT_COMPAT, 'UTF-8');
  75. * },
  76. *
  77. * // Character set for `htmlspecialchars`. Defaults to 'UTF-8'. Use 'UTF-8'.
  78. * 'charset' => 'ISO-8859-1',
  79. *
  80. * // A Mustache Logger instance. No logging will occur unless this is set.
  81. * 'logger' => new Mustache_StreamLogger('php://stderr'),
  82. * );
  83. *
  84. * @param array $options (default: array())
  85. */
  86. public function __construct(array $options = array())
  87. {
  88. if (isset($options['template_class_prefix'])) {
  89. $this->templateClassPrefix = $options['template_class_prefix'];
  90. }
  91. if (isset($options['cache'])) {
  92. $this->cache = $options['cache'];
  93. }
  94. if (isset($options['cache_file_mode'])) {
  95. $this->cacheFileMode = $options['cache_file_mode'];
  96. }
  97. if (isset($options['loader'])) {
  98. $this->setLoader($options['loader']);
  99. }
  100. if (isset($options['partials_loader'])) {
  101. $this->setPartialsLoader($options['partials_loader']);
  102. }
  103. if (isset($options['partials'])) {
  104. $this->setPartials($options['partials']);
  105. }
  106. if (isset($options['helpers'])) {
  107. $this->setHelpers($options['helpers']);
  108. }
  109. if (isset($options['escape'])) {
  110. if (!is_callable($options['escape'])) {
  111. throw new InvalidArgumentException('Mustache Constructor "escape" option must be callable');
  112. }
  113. $this->escape = $options['escape'];
  114. }
  115. if (isset($options['charset'])) {
  116. $this->charset = $options['charset'];
  117. }
  118. if (isset($options['logger'])) {
  119. $this->setLogger($options['logger']);
  120. }
  121. }
  122. /**
  123. * Shortcut 'render' invocation.
  124. *
  125. * Equivalent to calling `$mustache->loadTemplate($template)->render($data);`
  126. *
  127. * @see Mustache_Engine::loadTemplate
  128. * @see Mustache_Template::render
  129. *
  130. * @param string $template
  131. * @param mixed $data
  132. *
  133. * @return string Rendered template
  134. */
  135. public function render($template, $data)
  136. {
  137. return $this->loadTemplate($template)->render($data);
  138. }
  139. /**
  140. * Get the current Mustache escape callback.
  141. *
  142. * @return mixed Callable or null
  143. */
  144. public function getEscape()
  145. {
  146. return $this->escape;
  147. }
  148. /**
  149. * Get the current Mustache character set.
  150. *
  151. * @return string
  152. */
  153. public function getCharset()
  154. {
  155. return $this->charset;
  156. }
  157. /**
  158. * Set the Mustache template Loader instance.
  159. *
  160. * @param Mustache_Loader $loader
  161. */
  162. public function setLoader(Mustache_Loader $loader)
  163. {
  164. $this->loader = $loader;
  165. }
  166. /**
  167. * Get the current Mustache template Loader instance.
  168. *
  169. * If no Loader instance has been explicitly specified, this method will instantiate and return
  170. * a StringLoader instance.
  171. *
  172. * @return Mustache_Loader
  173. */
  174. public function getLoader()
  175. {
  176. if (!isset($this->loader)) {
  177. $this->loader = new Mustache_Loader_StringLoader;
  178. }
  179. return $this->loader;
  180. }
  181. /**
  182. * Set the Mustache partials Loader instance.
  183. *
  184. * @param Mustache_Loader $partialsLoader
  185. */
  186. public function setPartialsLoader(Mustache_Loader $partialsLoader)
  187. {
  188. $this->partialsLoader = $partialsLoader;
  189. }
  190. /**
  191. * Get the current Mustache partials Loader instance.
  192. *
  193. * If no Loader instance has been explicitly specified, this method will instantiate and return
  194. * an ArrayLoader instance.
  195. *
  196. * @return Mustache_Loader
  197. */
  198. public function getPartialsLoader()
  199. {
  200. if (!isset($this->partialsLoader)) {
  201. $this->partialsLoader = new Mustache_Loader_ArrayLoader;
  202. }
  203. return $this->partialsLoader;
  204. }
  205. /**
  206. * Set partials for the current partials Loader instance.
  207. *
  208. * @throws RuntimeException If the current Loader instance is immutable
  209. *
  210. * @param array $partials (default: array())
  211. */
  212. public function setPartials(array $partials = array())
  213. {
  214. $loader = $this->getPartialsLoader();
  215. if (!$loader instanceof Mustache_Loader_MutableLoader) {
  216. throw new RuntimeException('Unable to set partials on an immutable Mustache Loader instance');
  217. }
  218. $loader->setTemplates($partials);
  219. }
  220. /**
  221. * Set an array of Mustache helpers.
  222. *
  223. * An array of 'helpers'. Helpers can be global variables or objects, closures (e.g. for higher order sections), or
  224. * any other valid Mustache context value. They will be prepended to the context stack, so they will be available in
  225. * any template loaded by this Mustache instance.
  226. *
  227. * @throws InvalidArgumentException if $helpers is not an array or Traversable
  228. *
  229. * @param array|Traversable $helpers
  230. */
  231. public function setHelpers($helpers)
  232. {
  233. if (!is_array($helpers) && !$helpers instanceof Traversable) {
  234. throw new InvalidArgumentException('setHelpers expects an array of helpers');
  235. }
  236. $this->getHelpers()->clear();
  237. foreach ($helpers as $name => $helper) {
  238. $this->addHelper($name, $helper);
  239. }
  240. }
  241. /**
  242. * Get the current set of Mustache helpers.
  243. *
  244. * @see Mustache_Engine::setHelpers
  245. *
  246. * @return Mustache_HelperCollection
  247. */
  248. public function getHelpers()
  249. {
  250. if (!isset($this->helpers)) {
  251. $this->helpers = new Mustache_HelperCollection;
  252. }
  253. return $this->helpers;
  254. }
  255. /**
  256. * Add a new Mustache helper.
  257. *
  258. * @see Mustache_Engine::setHelpers
  259. *
  260. * @param string $name
  261. * @param mixed $helper
  262. */
  263. public function addHelper($name, $helper)
  264. {
  265. $this->getHelpers()->add($name, $helper);
  266. }
  267. /**
  268. * Get a Mustache helper by name.
  269. *
  270. * @see Mustache_Engine::setHelpers
  271. *
  272. * @param string $name
  273. *
  274. * @return mixed Helper
  275. */
  276. public function getHelper($name)
  277. {
  278. return $this->getHelpers()->get($name);
  279. }
  280. /**
  281. * Check whether this Mustache instance has a helper.
  282. *
  283. * @see Mustache_Engine::setHelpers
  284. *
  285. * @param string $name
  286. *
  287. * @return boolean True if the helper is present
  288. */
  289. public function hasHelper($name)
  290. {
  291. return $this->getHelpers()->has($name);
  292. }
  293. /**
  294. * Remove a helper by name.
  295. *
  296. * @see Mustache_Engine::setHelpers
  297. *
  298. * @param string $name
  299. */
  300. public function removeHelper($name)
  301. {
  302. $this->getHelpers()->remove($name);
  303. }
  304. /**
  305. * Set the Mustache Logger instance.
  306. *
  307. * @param Mustache_Logger $logger
  308. */
  309. public function setLogger(Mustache_Logger $logger)
  310. {
  311. $this->logger = $logger;
  312. }
  313. /**
  314. * Get the current Mustache Logger instance.
  315. *
  316. * @return Mustache_Logger
  317. */
  318. public function getLogger()
  319. {
  320. return $this->logger;
  321. }
  322. /**
  323. * Set the Mustache Tokenizer instance.
  324. *
  325. * @param Mustache_Tokenizer $tokenizer
  326. */
  327. public function setTokenizer(Mustache_Tokenizer $tokenizer)
  328. {
  329. $this->tokenizer = $tokenizer;
  330. }
  331. /**
  332. * Get the current Mustache Tokenizer instance.
  333. *
  334. * If no Tokenizer instance has been explicitly specified, this method will instantiate and return a new one.
  335. *
  336. * @return Mustache_Tokenizer
  337. */
  338. public function getTokenizer()
  339. {
  340. if (!isset($this->tokenizer)) {
  341. $this->tokenizer = new Mustache_Tokenizer;
  342. }
  343. return $this->tokenizer;
  344. }
  345. /**
  346. * Set the Mustache Parser instance.
  347. *
  348. * @param Mustache_Parser $parser
  349. */
  350. public function setParser(Mustache_Parser $parser)
  351. {
  352. $this->parser = $parser;
  353. }
  354. /**
  355. * Get the current Mustache Parser instance.
  356. *
  357. * If no Parser instance has been explicitly specified, this method will instantiate and return a new one.
  358. *
  359. * @return Mustache_Parser
  360. */
  361. public function getParser()
  362. {
  363. if (!isset($this->parser)) {
  364. $this->parser = new Mustache_Parser;
  365. }
  366. return $this->parser;
  367. }
  368. /**
  369. * Set the Mustache Compiler instance.
  370. *
  371. * @param Mustache_Compiler $compiler
  372. */
  373. public function setCompiler(Mustache_Compiler $compiler)
  374. {
  375. $this->compiler = $compiler;
  376. }
  377. /**
  378. * Get the current Mustache Compiler instance.
  379. *
  380. * If no Compiler instance has been explicitly specified, this method will instantiate and return a new one.
  381. *
  382. * @return Mustache_Compiler
  383. */
  384. public function getCompiler()
  385. {
  386. if (!isset($this->compiler)) {
  387. $this->compiler = new Mustache_Compiler;
  388. }
  389. return $this->compiler;
  390. }
  391. /**
  392. * Helper method to generate a Mustache template class.
  393. *
  394. * @param string $source
  395. *
  396. * @return string Mustache Template class name
  397. */
  398. public function getTemplateClassName($source)
  399. {
  400. return $this->templateClassPrefix . md5(sprintf(
  401. 'version:%s,escape:%s,charset:%s,source:%s',
  402. self::VERSION,
  403. isset($this->escape) ? 'custom' : 'default',
  404. $this->charset,
  405. $source
  406. ));
  407. }
  408. /**
  409. * Load a Mustache Template by name.
  410. *
  411. * @param string $name
  412. *
  413. * @return Mustache_Template
  414. */
  415. public function loadTemplate($name)
  416. {
  417. return $this->loadSource($this->getLoader()->load($name));
  418. }
  419. /**
  420. * Load a Mustache partial Template by name.
  421. *
  422. * This is a helper method used internally by Template instances for loading partial templates. You can most likely
  423. * ignore it completely.
  424. *
  425. * @param string $name
  426. *
  427. * @return Mustache_Template
  428. */
  429. public function loadPartial($name)
  430. {
  431. try {
  432. return $this->loadSource($this->getPartialsLoader()->load($name));
  433. } catch (InvalidArgumentException $e) {
  434. // If the named partial cannot be found, log then return null.
  435. $this->log(
  436. Mustache_Logger::WARNING,
  437. sprintf('Partial not found: "%s"', $name),
  438. array('name' => $name)
  439. );
  440. }
  441. }
  442. /**
  443. * Load a Mustache lambda Template by source.
  444. *
  445. * This is a helper method used by Template instances to generate subtemplates for Lambda sections. You can most
  446. * likely ignore it completely.
  447. *
  448. * @param string $source
  449. * @param string $delims (default: null)
  450. *
  451. * @return Mustache_Template
  452. */
  453. public function loadLambda($source, $delims = null)
  454. {
  455. if ($delims !== null) {
  456. $source = $delims . "\n" . $source;
  457. }
  458. return $this->loadSource($source);
  459. }
  460. /**
  461. * Instantiate and return a Mustache Template instance by source.
  462. *
  463. * @see Mustache_Engine::loadTemplate
  464. * @see Mustache_Engine::loadPartial
  465. * @see Mustache_Engine::loadLambda
  466. *
  467. * @param string $source
  468. *
  469. * @return Mustache_Template
  470. */
  471. private function loadSource($source)
  472. {
  473. $className = $this->getTemplateClassName($source);
  474. if (!isset($this->templates[$className])) {
  475. if (!class_exists($className, false)) {
  476. if ($fileName = $this->getCacheFilename($source)) {
  477. if (!is_file($fileName)) {
  478. $this->log(
  479. Mustache_Logger::DEBUG,
  480. sprintf('Writing "%s" class to template cache: "%s"', $className, $fileName),
  481. array('className' => $className, 'fileName' => $fileName)
  482. );
  483. $this->writeCacheFile($fileName, $this->compile($source));
  484. }
  485. require_once $fileName;
  486. } else {
  487. $this->log(
  488. Mustache_Logger::WARNING,
  489. sprintf('Template cache disabled, evaluating "%s" class at runtime', $className),
  490. array('className' => $className)
  491. );
  492. eval('?>'.$this->compile($source));
  493. }
  494. }
  495. $this->log(
  496. Mustache_Logger::DEBUG,
  497. sprintf('Instantiating template: "%s"', $className),
  498. array('className' => $className)
  499. );
  500. $this->templates[$className] = new $className($this);
  501. }
  502. return $this->templates[$className];
  503. }
  504. /**
  505. * Helper method to tokenize a Mustache template.
  506. *
  507. * @see Mustache_Tokenizer::scan
  508. *
  509. * @param string $source
  510. *
  511. * @return array Tokens
  512. */
  513. private function tokenize($source)
  514. {
  515. return $this->getTokenizer()->scan($source);
  516. }
  517. /**
  518. * Helper method to parse a Mustache template.
  519. *
  520. * @see Mustache_Parser::parse
  521. *
  522. * @param string $source
  523. *
  524. * @return array Token tree
  525. */
  526. private function parse($source)
  527. {
  528. return $this->getParser()->parse($this->tokenize($source));
  529. }
  530. /**
  531. * Helper method to compile a Mustache template.
  532. *
  533. * @see Mustache_Compiler::compile
  534. *
  535. * @param string $source
  536. *
  537. * @return string generated Mustache template class code
  538. */
  539. private function compile($source)
  540. {
  541. $tree = $this->parse($source);
  542. $name = $this->getTemplateClassName($source);
  543. $this->log(
  544. Mustache_Logger::INFO,
  545. sprintf('Compiling template to "%s" class', $name),
  546. array('name' => $name)
  547. );
  548. return $this->getCompiler()->compile($source, $tree, $name, isset($this->escape), $this->charset);
  549. }
  550. /**
  551. * Helper method to generate a Mustache Template class cache filename.
  552. *
  553. * @param string $source
  554. *
  555. * @return string Mustache Template class cache filename
  556. */
  557. private function getCacheFilename($source)
  558. {
  559. if ($this->cache) {
  560. return sprintf('%s/%s.php', $this->cache, $this->getTemplateClassName($source));
  561. }
  562. }
  563. /**
  564. * Helper method to dump a generated Mustache Template subclass to the file cache.
  565. *
  566. * @throws RuntimeException if unable to create the cache directory or write to $fileName.
  567. *
  568. * @param string $fileName
  569. * @param string $source
  570. *
  571. * @codeCoverageIgnore
  572. */
  573. private function writeCacheFile($fileName, $source)
  574. {
  575. $dirName = dirname($fileName);
  576. if (!is_dir($dirName)) {
  577. $this->log(
  578. Mustache_Logger::INFO,
  579. sprintf('Creating Mustache template cache directory: "%s"', $dirName),
  580. array('dirName' => $dirName)
  581. );
  582. @mkdir($dirName, 0777, true);
  583. if (!is_dir($dirName)) {
  584. throw new RuntimeException(sprintf('Failed to create cache directory "%s".', $dirName));
  585. }
  586. }
  587. $this->log(
  588. Mustache_Logger::DEBUG,
  589. sprintf('Caching compiled template to "%s"', dirname($fileName)),
  590. array('filename' => $fileName)
  591. );
  592. $tempFile = tempnam($dirName, basename($fileName));
  593. if (false !== @file_put_contents($tempFile, $source)) {
  594. if (@rename($tempFile, $fileName)) {
  595. $mode = isset($this->cacheFileMode) ? $this->cacheFileMode : (0666 & ~umask());
  596. @chmod($fileName, $mode);
  597. return;
  598. }
  599. $this->log(
  600. Mustache_Logger::ERROR,
  601. sprintf('Unable to rename Mustache temp cache file: "%s" -> "%s"', $tempFile, $fileName),
  602. array('tempFile' => $tempFile, 'fileName' => $fileName)
  603. );
  604. }
  605. throw new RuntimeException(sprintf('Failed to write cache file "%s".', $fileName));
  606. }
  607. /**
  608. * Add a log record if logging is enabled.
  609. *
  610. * @param integer $level The logging level
  611. * @param string $message The log message
  612. * @param array $context The log context
  613. */
  614. private function log($level, $message, array $context = array())
  615. {
  616. if (isset($this->logger)) {
  617. $this->logger->log($level, $message, $context);
  618. }
  619. }
  620. }