FilesystemLoader.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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\Bundle\TwigBundle\Loader;
  11. use Symfony\Component\Templating\TemplateNameParserInterface;
  12. use Symfony\Component\Config\FileLocatorInterface;
  13. use Symfony\Component\Templating\TemplateReferenceInterface;
  14. /**
  15. * FilesystemLoader extends the default Twig filesystem loader
  16. * to work with the Symfony2 paths.
  17. *
  18. * @author Fabien Potencier <fabien@symfony.com>
  19. */
  20. class FilesystemLoader extends \Twig_Loader_Filesystem
  21. {
  22. protected $locator;
  23. protected $parser;
  24. protected $cache;
  25. /**
  26. * Constructor.
  27. *
  28. * @param FileLocatorInterface $locator A FileLocatorInterface instance
  29. * @param TemplateNameParserInterface $parser A TemplateNameParserInterface instance
  30. */
  31. public function __construct(FileLocatorInterface $locator, TemplateNameParserInterface $parser)
  32. {
  33. $this->locator = $locator;
  34. $this->parser = $parser;
  35. $this->cache = array();
  36. }
  37. /**
  38. * Returns the path to the template file
  39. *
  40. * @param $name The template logical name
  41. *
  42. * @return string The path to the template file
  43. */
  44. protected function findTemplate($name)
  45. {
  46. try {
  47. $tpl = $this->parser->parse($name);
  48. } catch (\Exception $e) {
  49. return parent::findTemplate($name);
  50. }
  51. if (isset($this->cache[$key = $tpl->getLogicalName()])) {
  52. return $this->cache[$key];
  53. }
  54. $file = null;
  55. $previous = null;
  56. try {
  57. $file = $this->locator->locate($tpl);
  58. } catch (\InvalidArgumentException $e) {
  59. $previous = $e;
  60. }
  61. if (false === $file || null === $file) {
  62. throw new \Twig_Error_Loader(sprintf('Unable to find template "%s".', $tpl), -1, null, $previous);
  63. }
  64. return $this->cache[$key] = $file;
  65. }
  66. }