TemplateLocator.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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\FrameworkBundle\Templating\Loader;
  11. use Symfony\Component\Config\FileLocatorInterface;
  12. use Symfony\Component\Templating\TemplateReferenceInterface;
  13. /**
  14. * TemplateLocator locates templates in bundles.
  15. *
  16. * @author Fabien Potencier <fabien@symfony.com>
  17. */
  18. class TemplateLocator implements FileLocatorInterface
  19. {
  20. protected $locator;
  21. protected $cache;
  22. private $cacheHits = array();
  23. /**
  24. * @param FileLocatorInterface $locator A FileLocatorInterface instance
  25. * @param string $cacheDir The cache path
  26. */
  27. public function __construct(FileLocatorInterface $locator, $cacheDir = null)
  28. {
  29. if (null !== $cacheDir && is_file($cache = $cacheDir.'/templates.php')) {
  30. $this->cache = require $cache;
  31. }
  32. $this->locator = $locator;
  33. }
  34. /**
  35. * Returns a full path for a given file.
  36. *
  37. * @return string The full path for the file
  38. */
  39. protected function getCacheKey($template)
  40. {
  41. return $template->getLogicalName();
  42. }
  43. /**
  44. * Returns a full path for a given file.
  45. *
  46. * @param TemplateReferenceInterface $template A template
  47. * @param string $currentPath Unused
  48. * @param bool $first Unused
  49. *
  50. * @return string The full path for the file
  51. *
  52. * @throws \InvalidArgumentException When the template is not an instance of TemplateReferenceInterface
  53. * @throws \InvalidArgumentException When the template file can not be found
  54. */
  55. public function locate($template, $currentPath = null, $first = true)
  56. {
  57. if (!$template instanceof TemplateReferenceInterface) {
  58. throw new \InvalidArgumentException('The template must be an instance of TemplateReferenceInterface.');
  59. }
  60. $key = $this->getCacheKey($template);
  61. if (isset($this->cacheHits[$key])) {
  62. return $this->cacheHits[$key];
  63. }
  64. if (isset($this->cache[$key])) {
  65. return $this->cacheHits[$key] = realpath($this->cache[$key]) ?: $this->cache[$key];
  66. }
  67. try {
  68. return $this->cacheHits[$key] = $this->locator->locate($template->getPath(), $currentPath);
  69. } catch (\InvalidArgumentException $e) {
  70. throw new \InvalidArgumentException(sprintf('Unable to find template "%s" : "%s".', $template, $e->getMessage()), 0, $e);
  71. }
  72. }
  73. }