FilesystemLoader.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. /**
  14. * FilesystemLoader extends the default Twig filesystem loader
  15. * to work with the Symfony2 paths.
  16. *
  17. * @author Fabien Potencier <fabien@symfony.com>
  18. */
  19. class FilesystemLoader extends \Twig_Loader_Filesystem
  20. {
  21. protected $locator;
  22. protected $parser;
  23. /**
  24. * Constructor.
  25. *
  26. * @param FileLocatorInterface $locator A FileLocatorInterface instance
  27. * @param TemplateNameParserInterface $parser A TemplateNameParserInterface instance
  28. */
  29. public function __construct(FileLocatorInterface $locator, TemplateNameParserInterface $parser)
  30. {
  31. parent::__construct(array());
  32. $this->locator = $locator;
  33. $this->parser = $parser;
  34. $this->cache = array();
  35. }
  36. /**
  37. * Returns the path to the template file.
  38. *
  39. * The file locator is used to locate the template when the naming convention
  40. * is the symfony one (i.e. the name can be parsed).
  41. * Otherwise the template is located using the locator from the twig library.
  42. *
  43. * @param string|TemplateReferenceInterface $template The template
  44. *
  45. * @return string The path to the template file
  46. *
  47. * @throws \Twig_Error_Loader if the template could not be found
  48. */
  49. protected function findTemplate($template)
  50. {
  51. $logicalName = (string) $template;
  52. if (isset($this->cache[$logicalName])) {
  53. return $this->cache[$logicalName];
  54. }
  55. $file = null;
  56. $previous = null;
  57. try {
  58. $template = $this->parser->parse($template);
  59. try {
  60. $file = $this->locator->locate($template);
  61. } catch (\InvalidArgumentException $e) {
  62. $previous = $e;
  63. }
  64. } catch (\Exception $e) {
  65. try {
  66. $file = parent::findTemplate($template);
  67. } catch (\Twig_Error_Loader $e) {
  68. $previous = $e;
  69. }
  70. }
  71. if (false === $file || null === $file) {
  72. throw new \Twig_Error_Loader(sprintf('Unable to find template "%s".', $logicalName), -1, null, $previous);
  73. }
  74. return $this->cache[$logicalName] = $file;
  75. }
  76. }