PhpEngine.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Templating;
  11. use Symfony\Component\Templating\Storage\Storage;
  12. use Symfony\Component\Templating\Storage\FileStorage;
  13. use Symfony\Component\Templating\Storage\StringStorage;
  14. use Symfony\Component\Templating\Helper\HelperInterface;
  15. use Symfony\Component\Templating\Loader\LoaderInterface;
  16. /**
  17. * PhpEngine is an engine able to render PHP templates.
  18. *
  19. * @author Fabien Potencier <fabien@symfony.com>
  20. *
  21. * @api
  22. */
  23. class PhpEngine implements EngineInterface, \ArrayAccess
  24. {
  25. protected $loader;
  26. protected $current;
  27. protected $helpers;
  28. protected $parents;
  29. protected $stack;
  30. protected $charset;
  31. protected $cache;
  32. protected $escapers;
  33. protected $globals;
  34. protected $parser;
  35. /**
  36. * Constructor.
  37. *
  38. * @param TemplateNameParserInterface $parser A TemplateNameParserInterface instance
  39. * @param LoaderInterface $loader A loader instance
  40. * @param array $helpers An array of helper instances
  41. */
  42. public function __construct(TemplateNameParserInterface $parser, LoaderInterface $loader, array $helpers = array())
  43. {
  44. $this->parser = $parser;
  45. $this->loader = $loader;
  46. $this->parents = array();
  47. $this->stack = array();
  48. $this->charset = 'UTF-8';
  49. $this->cache = array();
  50. $this->globals = array();
  51. $this->setHelpers($helpers);
  52. $this->initializeEscapers();
  53. foreach ($this->escapers as $context => $escaper) {
  54. $this->setEscaper($context, $escaper);
  55. }
  56. }
  57. /**
  58. * Renders a template.
  59. *
  60. * @param mixed $name A template name or a TemplateReferenceInterface instance
  61. * @param array $parameters An array of parameters to pass to the template
  62. *
  63. * @return string The evaluated template as a string
  64. *
  65. * @throws \InvalidArgumentException if the template does not exist
  66. * @throws \RuntimeException if the template cannot be rendered
  67. *
  68. * @api
  69. */
  70. public function render($name, array $parameters = array())
  71. {
  72. $storage = $this->load($name);
  73. $key = md5(serialize($storage));
  74. $this->current = $key;
  75. $this->parents[$key] = null;
  76. // attach the global variables
  77. $parameters = array_replace($this->getGlobals(), $parameters);
  78. // render
  79. if (false === $content = $this->evaluate($storage, $parameters)) {
  80. throw new \RuntimeException(sprintf('The template "%s" cannot be rendered.', $this->parser->parse($name)));
  81. }
  82. // decorator
  83. if ($this->parents[$key]) {
  84. $slots = $this->get('slots');
  85. $this->stack[] = $slots->get('_content');
  86. $slots->set('_content', $content);
  87. $content = $this->render($this->parents[$key], $parameters);
  88. $slots->set('_content', array_pop($this->stack));
  89. }
  90. return $content;
  91. }
  92. /**
  93. * Returns true if the template exists.
  94. *
  95. * @param mixed $name A template name or a TemplateReferenceInterface instance
  96. *
  97. * @return Boolean true if the template exists, false otherwise
  98. *
  99. * @api
  100. */
  101. public function exists($name)
  102. {
  103. try {
  104. $this->load($name);
  105. } catch (\InvalidArgumentException $e) {
  106. return false;
  107. }
  108. return true;
  109. }
  110. /**
  111. * Returns true if this class is able to render the given template.
  112. *
  113. * @param mixed $name A template name or a TemplateReferenceInterface instance
  114. *
  115. * @return Boolean true if this class supports the given resource, false otherwise
  116. *
  117. * @api
  118. */
  119. public function supports($name)
  120. {
  121. $template = $this->parser->parse($name);
  122. return 'php' === $template->get('engine');
  123. }
  124. /**
  125. * Evaluates a template.
  126. *
  127. * @param Storage $template The template to render
  128. * @param array $parameters An array of parameters to pass to the template
  129. *
  130. * @return string|false The evaluated template, or false if the engine is unable to render the template
  131. */
  132. protected function evaluate(Storage $template, array $parameters = array())
  133. {
  134. $__template__ = $template;
  135. if ($__template__ instanceof FileStorage) {
  136. extract($parameters);
  137. $view = $this;
  138. ob_start();
  139. require $__template__;
  140. return ob_get_clean();
  141. } elseif ($__template__ instanceof StringStorage) {
  142. extract($parameters);
  143. $view = $this;
  144. ob_start();
  145. eval('; ?>'.$__template__.'<?php ;');
  146. return ob_get_clean();
  147. }
  148. return false;
  149. }
  150. /**
  151. * Gets a helper value.
  152. *
  153. * @param string $name The helper name
  154. *
  155. * @return mixed The helper value
  156. *
  157. * @throws \InvalidArgumentException if the helper is not defined
  158. *
  159. * @api
  160. */
  161. public function offsetGet($name)
  162. {
  163. return $this->get($name);
  164. }
  165. /**
  166. * Returns true if the helper is defined.
  167. *
  168. * @param string $name The helper name
  169. *
  170. * @return Boolean true if the helper is defined, false otherwise
  171. *
  172. * @api
  173. */
  174. public function offsetExists($name)
  175. {
  176. return isset($this->helpers[$name]);
  177. }
  178. /**
  179. * Sets a helper.
  180. *
  181. * @param HelperInterface $name The helper instance
  182. * @param string $value An alias
  183. *
  184. * @api
  185. */
  186. public function offsetSet($name, $value)
  187. {
  188. $this->set($name, $value);
  189. }
  190. /**
  191. * Removes a helper.
  192. *
  193. * @param string $name The helper name
  194. *
  195. * @api
  196. */
  197. public function offsetUnset($name)
  198. {
  199. throw new \LogicException(sprintf('You can\'t unset a helper (%s).', $name));
  200. }
  201. /**
  202. * @param Helper[] $helpers An array of helper
  203. *
  204. * @api
  205. */
  206. public function addHelpers(array $helpers)
  207. {
  208. foreach ($helpers as $alias => $helper) {
  209. $this->set($helper, is_int($alias) ? null : $alias);
  210. }
  211. }
  212. /**
  213. * Sets the helpers.
  214. *
  215. * @params Helper[] $helpers An array of helper
  216. *
  217. * @api
  218. */
  219. public function setHelpers(array $helpers)
  220. {
  221. $this->helpers = array();
  222. $this->addHelpers($helpers);
  223. }
  224. /**
  225. * Sets a helper.
  226. *
  227. * @param HelperInterface $helper The helper instance
  228. * @param string $alias An alias
  229. *
  230. * @api
  231. */
  232. public function set(HelperInterface $helper, $alias = null)
  233. {
  234. $this->helpers[$helper->getName()] = $helper;
  235. if (null !== $alias) {
  236. $this->helpers[$alias] = $helper;
  237. }
  238. $helper->setCharset($this->charset);
  239. }
  240. /**
  241. * Returns true if the helper if defined.
  242. *
  243. * @param string $name The helper name
  244. *
  245. * @return Boolean true if the helper is defined, false otherwise
  246. *
  247. * @api
  248. */
  249. public function has($name)
  250. {
  251. return isset($this->helpers[$name]);
  252. }
  253. /**
  254. * Gets a helper value.
  255. *
  256. * @param string $name The helper name
  257. *
  258. * @return HelperInterface The helper instance
  259. *
  260. * @throws \InvalidArgumentException if the helper is not defined
  261. *
  262. * @api
  263. */
  264. public function get($name)
  265. {
  266. if (!isset($this->helpers[$name])) {
  267. throw new \InvalidArgumentException(sprintf('The helper "%s" is not defined.', $name));
  268. }
  269. return $this->helpers[$name];
  270. }
  271. /**
  272. * Decorates the current template with another one.
  273. *
  274. * @param string $template The decorator logical name
  275. *
  276. * @api
  277. */
  278. public function extend($template)
  279. {
  280. $this->parents[$this->current] = $template;
  281. }
  282. /**
  283. * Escapes a string by using the current charset.
  284. *
  285. * @param mixed $value A variable to escape
  286. * @param string $context The context name
  287. *
  288. * @return string The escaped value
  289. *
  290. * @api
  291. */
  292. public function escape($value, $context = 'html')
  293. {
  294. return call_user_func($this->getEscaper($context), $value);
  295. }
  296. /**
  297. * Sets the charset to use.
  298. *
  299. * @param string $charset The charset
  300. *
  301. * @api
  302. */
  303. public function setCharset($charset)
  304. {
  305. $this->charset = $charset;
  306. }
  307. /**
  308. * Gets the current charset.
  309. *
  310. * @return string The current charset
  311. *
  312. * @api
  313. */
  314. public function getCharset()
  315. {
  316. return $this->charset;
  317. }
  318. /**
  319. * Adds an escaper for the given context.
  320. *
  321. * @param string $context The escaper context (html, js, ...)
  322. * @param mixed $escaper A PHP callable
  323. *
  324. * @api
  325. */
  326. public function setEscaper($context, $escaper)
  327. {
  328. $this->escapers[$context] = $escaper;
  329. }
  330. /**
  331. * Gets an escaper for a given context.
  332. *
  333. * @param string $context The context name
  334. *
  335. * @return mixed $escaper A PHP callable
  336. *
  337. * @api
  338. */
  339. public function getEscaper($context)
  340. {
  341. if (!isset($this->escapers[$context])) {
  342. throw new \InvalidArgumentException(sprintf('No registered escaper for context "%s".', $context));
  343. }
  344. return $this->escapers[$context];
  345. }
  346. /**
  347. * @param string $name
  348. * @param mixed $value
  349. *
  350. * @api
  351. */
  352. public function addGlobal($name, $value)
  353. {
  354. $this->globals[$name] = $value;
  355. }
  356. /**
  357. * Returns the assigned globals.
  358. *
  359. * @return array
  360. *
  361. * @api
  362. */
  363. public function getGlobals()
  364. {
  365. return $this->globals;
  366. }
  367. /**
  368. * Initializes the built-in escapers.
  369. *
  370. * Each function specifies a way for applying a transformation to a string
  371. * passed to it. The purpose is for the string to be "escaped" so it is
  372. * suitable for the format it is being displayed in.
  373. *
  374. * For example, the string: "It's required that you enter a username & password.\n"
  375. * If this were to be displayed as HTML it would be sensible to turn the
  376. * ampersand into '&amp;' and the apostrophe into '&aps;'. However if it were
  377. * going to be used as a string in JavaScript to be displayed in an alert box
  378. * it would be right to leave the string as-is, but c-escape the apostrophe and
  379. * the new line.
  380. *
  381. * For each function there is a define to avoid problems with strings being
  382. * incorrectly specified.
  383. */
  384. protected function initializeEscapers()
  385. {
  386. $that = $this;
  387. $this->escapers = array(
  388. 'html' =>
  389. /**
  390. * Runs the PHP function htmlspecialchars on the value passed.
  391. *
  392. * @param string $value the value to escape
  393. *
  394. * @return string the escaped value
  395. */
  396. function ($value) use ($that)
  397. {
  398. // Numbers and Boolean values get turned into strings which can cause problems
  399. // with type comparisons (e.g. === or is_int() etc).
  400. return is_string($value) ? htmlspecialchars($value, ENT_QUOTES, $that->getCharset(), false) : $value;
  401. },
  402. 'js' =>
  403. /**
  404. * A function that escape all non-alphanumeric characters
  405. * into their \xHH or \uHHHH representations
  406. *
  407. * @param string $value the value to escape
  408. * @return string the escaped value
  409. */
  410. function ($value) use ($that)
  411. {
  412. if ('UTF-8' != $that->getCharset()) {
  413. $value = $that->convertEncoding($value, 'UTF-8', $that->getCharset());
  414. }
  415. $callback = function ($matches) use ($that)
  416. {
  417. $char = $matches[0];
  418. // \xHH
  419. if (!isset($char[1])) {
  420. return '\\x'.substr('00'.bin2hex($char), -2);
  421. }
  422. // \uHHHH
  423. $char = $that->convertEncoding($char, 'UTF-16BE', 'UTF-8');
  424. return '\\u'.substr('0000'.bin2hex($char), -4);
  425. };
  426. if (null === $value = preg_replace_callback('#[^\p{L}\p{N} ]#u', $callback, $value)) {
  427. throw new \InvalidArgumentException('The string to escape is not a valid UTF-8 string.');
  428. }
  429. if ('UTF-8' != $that->getCharset()) {
  430. $value = $that->convertEncoding($value, $that->getCharset(), 'UTF-8');
  431. }
  432. return $value;
  433. },
  434. );
  435. }
  436. /**
  437. * Convert a string from one encoding to another.
  438. *
  439. * @param string $string The string to convert
  440. * @param string $to The input encoding
  441. * @param string $from The output encoding
  442. *
  443. * @return string The string with the new encoding
  444. *
  445. * @throws \RuntimeException if no suitable encoding function is found (iconv or mbstring)
  446. */
  447. public function convertEncoding($string, $to, $from)
  448. {
  449. if (function_exists('iconv')) {
  450. return iconv($from, $to, $string);
  451. } elseif (function_exists('mb_convert_encoding')) {
  452. return mb_convert_encoding($string, $to, $from);
  453. }
  454. throw new \RuntimeException('No suitable convert encoding function (use UTF-8 as your encoding or install the iconv or mbstring extension).');
  455. }
  456. /**
  457. * Gets the loader associated with this engine.
  458. *
  459. * @return LoaderInterface A LoaderInterface instance
  460. */
  461. public function getLoader()
  462. {
  463. return $this->loader;
  464. }
  465. /**
  466. * Loads the given template.
  467. *
  468. * @param mixed $name A template name or a TemplateReferenceInterface instance
  469. *
  470. * @return Storage A Storage instance
  471. *
  472. * @throws \InvalidArgumentException if the template cannot be found
  473. */
  474. protected function load($name)
  475. {
  476. $template = $this->parser->parse($name);
  477. $key = $template->getLogicalName();
  478. if (isset($this->cache[$key])) {
  479. return $this->cache[$key];
  480. }
  481. $storage = $this->loader->load($template);
  482. if (false === $storage) {
  483. throw new \InvalidArgumentException(sprintf('The template "%s" does not exist.', $template));
  484. }
  485. return $this->cache[$key] = $storage;
  486. }
  487. }