TemplateLocator.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. /**
  23. * Constructor.
  24. *
  25. * @param FileLocatorInterface $locator A FileLocatorInterface instance
  26. * @param string $cacheDir The cache path
  27. */
  28. public function __construct(FileLocatorInterface $locator, $cacheDir = null)
  29. {
  30. if (null !== $cacheDir && file_exists($cache = $cacheDir.'/templates.php')) {
  31. $this->cache = require $cache;
  32. }
  33. $this->locator = $locator;
  34. }
  35. /**
  36. * Returns a full path for a given file.
  37. *
  38. * @param TemplateReferenceInterface $template A template
  39. * @param string $currentPath Unused
  40. * @param Boolean $first Unused
  41. *
  42. * @return string The full path for the file
  43. *
  44. * @throws \InvalidArgumentException When the template is not an instance of TemplateReferenceInterface
  45. * @throws \InvalidArgumentException When the template file can not be found
  46. */
  47. public function locate($template, $currentPath = null, $first = true)
  48. {
  49. if (!$template instanceof TemplateReferenceInterface) {
  50. throw new \InvalidArgumentException("The template must be an instance of TemplateReferenceInterface.");
  51. }
  52. $key = $template->getLogicalName();
  53. if (isset($this->cache[$key])) {
  54. return $this->cache[$key];
  55. }
  56. try {
  57. return $this->cache[$key] = $this->locator->locate($template->getPath(), $currentPath);
  58. } catch (\InvalidArgumentException $e) {
  59. throw new \InvalidArgumentException(sprintf('Unable to find template "%s" in "%s".', $template, $currentPath), 0, $e);
  60. }
  61. }
  62. }