PhpEngine.php 16 KB

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