TemplateIterator.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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;
  11. use Symfony\Component\HttpKernel\KernelInterface;
  12. use Symfony\Component\Finder\Finder;
  13. /**
  14. * Iterator for all templates in bundles and in the application Resources directory.
  15. *
  16. * @author Fabien Potencier <fabien@symfony.com>
  17. */
  18. class TemplateIterator implements \IteratorAggregate
  19. {
  20. private $kernel;
  21. private $rootDir;
  22. private $templates;
  23. private $paths;
  24. /**
  25. * @param KernelInterface $kernel A KernelInterface instance
  26. * @param string $rootDir The directory where global templates can be stored
  27. * @param array $paths Additional Twig paths to warm
  28. */
  29. public function __construct(KernelInterface $kernel, $rootDir, array $paths = array())
  30. {
  31. $this->kernel = $kernel;
  32. $this->rootDir = $rootDir;
  33. $this->paths = $paths;
  34. }
  35. /**
  36. * {@inheritdoc}
  37. */
  38. public function getIterator()
  39. {
  40. if (null !== $this->templates) {
  41. return $this->templates;
  42. }
  43. $this->templates = $this->findTemplatesInDirectory($this->rootDir.'/Resources/views');
  44. foreach ($this->kernel->getBundles() as $bundle) {
  45. $name = $bundle->getName();
  46. if ('Bundle' === substr($name, -6)) {
  47. $name = substr($name, 0, -6);
  48. }
  49. $this->templates = array_merge(
  50. $this->templates,
  51. $this->findTemplatesInDirectory($bundle->getPath().'/Resources/views', $name),
  52. $this->findTemplatesInDirectory($this->rootDir.'/'.$bundle->getName().'/views', $name)
  53. );
  54. }
  55. foreach ($this->paths as $dir => $namespace) {
  56. $this->templates = array_merge($this->templates, $this->findTemplatesInDirectory($dir, $namespace));
  57. }
  58. return $this->templates = new \ArrayIterator(array_unique($this->templates));
  59. }
  60. /**
  61. * Find templates in the given directory.
  62. *
  63. * @param string $dir The directory where to look for templates
  64. * @param string|null $namespace The template namespace
  65. *
  66. * @return array
  67. */
  68. private function findTemplatesInDirectory($dir, $namespace = null)
  69. {
  70. if (!is_dir($dir)) {
  71. return array();
  72. }
  73. $templates = array();
  74. foreach (Finder::create()->files()->followLinks()->in($dir) as $file) {
  75. $templates[] = (null !== $namespace ? '@'.$namespace.'/' : '').str_replace('\\', '/', $file->getRelativePathname());
  76. }
  77. return $templates;
  78. }
  79. }