FilesystemLoader.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. namespace Symfony\Components\Templating\Loader;
  3. use Symfony\Components\Templating\Storage\Storage;
  4. use Symfony\Components\Templating\Storage\FileStorage;
  5. /*
  6. * This file is part of the symfony package.
  7. *
  8. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  9. *
  10. * For the full copyright and license information, please view the LICENSE
  11. * file that was distributed with this source code.
  12. */
  13. /**
  14. * FilesystemLoader is a loader that read templates from the filesystem.
  15. *
  16. * @package symfony
  17. * @subpackage templating
  18. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  19. */
  20. class FilesystemLoader extends Loader
  21. {
  22. protected
  23. $templatePathPatternPatterns = array();
  24. /**
  25. * Constructor.
  26. *
  27. * @param array $templatePathPatterns An array of path patterns to look for templates
  28. */
  29. public function __construct($templatePathPatterns)
  30. {
  31. if (!is_array($templatePathPatterns))
  32. {
  33. $templatePathPatterns = array($templatePathPatterns);
  34. }
  35. $this->templatePathPatterns = $templatePathPatterns;
  36. }
  37. /**
  38. * Loads a template.
  39. *
  40. * @param string $template The logical template name
  41. * @param string $renderer The renderer to use
  42. *
  43. * @return Storage|Boolean false if the template cannot be loaded, a Storage instance otherwise
  44. */
  45. public function load($template, $renderer = 'php')
  46. {
  47. if (self::isAbsolutePath($template) && file_exists($template))
  48. {
  49. return new FileStorage($template);
  50. }
  51. foreach ($this->templatePathPatterns as $templatePathPattern)
  52. {
  53. if (is_file($file = strtr($templatePathPattern, array('%name%' => $template, '%renderer%' => $renderer))))
  54. {
  55. if ($this->debugger)
  56. {
  57. $this->debugger->log(sprintf('Loaded template file "%s" (renderer: %s)', $file, $renderer));
  58. }
  59. return new FileStorage($file);
  60. }
  61. if ($this->debugger)
  62. {
  63. $this->debugger->log(sprintf('Failed loading template file "%s" (renderer: %s)', $file, $renderer));
  64. }
  65. }
  66. return false;
  67. }
  68. /**
  69. * Returns true if the file is an existing absolute path.
  70. *
  71. * @param string $file A path
  72. *
  73. * @return true if the path exists and is absolute, false otherwise
  74. */
  75. static protected function isAbsolutePath($file)
  76. {
  77. if ($file[0] == '/' || $file[0] == '\\' ||
  78. (strlen($file) > 3 && ctype_alpha($file[0]) &&
  79. $file[1] == ':' &&
  80. ($file[2] == '\\' || $file[2] == '/')
  81. )
  82. )
  83. {
  84. return true;
  85. }
  86. return false;
  87. }
  88. }