Loader.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. namespace Symfony\Bundle\TwigBundle\Loader;
  3. use Symfony\Component\Templating\Engine;
  4. use Symfony\Component\Templating\Storage\Storage;
  5. use Symfony\Component\Templating\Storage\FileStorage;
  6. /*
  7. * This file is part of the Symfony package.
  8. *
  9. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  10. *
  11. * For the full copyright and license information, please view the LICENSE
  12. * file that was distributed with this source code.
  13. */
  14. /**
  15. *
  16. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  17. */
  18. class Loader implements \Twig_LoaderInterface
  19. {
  20. protected $engine;
  21. public function setEngine(Engine $engine)
  22. {
  23. $this->engine = $engine;
  24. }
  25. /**
  26. * Gets the source code of a template, given its name.
  27. *
  28. * @param string $name string The name of the template to load
  29. *
  30. * @return string The template source code
  31. */
  32. public function getSource($name)
  33. {
  34. if ($name instanceof Storage) {
  35. return $name->getContent();
  36. }
  37. list($name, $options) = $this->engine->splitTemplateName($name);
  38. if ('twig' !== $options['renderer']) {
  39. throw new \LogicException(sprintf('A "%s" template cannot extend a "Twig" template.', $options['renderer']));
  40. }
  41. $template = $this->engine->getLoader()->load($name, $options);
  42. if (false === $template) {
  43. throw new \InvalidArgumentException(sprintf('The template "%s" does not exist (renderer: %s).', $name, $options['renderer']));
  44. }
  45. return $template->getContent();
  46. }
  47. /**
  48. * Gets the cache key to use for the cache for a given template name.
  49. *
  50. * @param string $name string The name of the template to load
  51. *
  52. * @return string The cache key
  53. */
  54. public function getCacheKey($name)
  55. {
  56. if ($name instanceof Storage) {
  57. return (string) $name;
  58. }
  59. list($name, $options) = $this->engine->splitTemplateName($name);
  60. return $name.'_'.serialize($options);
  61. }
  62. /**
  63. * Returns true if the template is still fresh.
  64. *
  65. * @param string $name The template name
  66. * @param timestamp $time The last modification time of the cached template
  67. */
  68. public function isFresh($name, $time)
  69. {
  70. if ($name instanceof Storage) {
  71. if ($name instanceof FileStorage) {
  72. return filemtime((string) $name) < $time;
  73. }
  74. return false;
  75. }
  76. list($name, $options) = $this->engine->splitTemplateName($name);
  77. return $this->engine->getLoader()->isFresh($name, $options, $time);
  78. }
  79. }