Array.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) 2009 Fabien Potencier
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. /**
  11. * Loads a template from an array.
  12. *
  13. * When using this loader with a cache mechanism, you should know that a new cache
  14. * key is generated each time a template content "changes" (the cache key being the
  15. * source code of the template). If you don't want to see your cache grows out of
  16. * control, you need to take care of clearing the old cache file by yourself.
  17. *
  18. * This loader should only be used for unit testing.
  19. *
  20. * @author Fabien Potencier <fabien@symfony.com>
  21. */
  22. class Twig_Loader_Array implements Twig_LoaderInterface, Twig_ExistsLoaderInterface
  23. {
  24. protected $templates = array();
  25. /**
  26. * Constructor.
  27. *
  28. * @param array $templates An array of templates (keys are the names, and values are the source code)
  29. */
  30. public function __construct(array $templates)
  31. {
  32. $this->templates = $templates;
  33. }
  34. /**
  35. * Adds or overrides a template.
  36. *
  37. * @param string $name The template name
  38. * @param string $template The template source
  39. */
  40. public function setTemplate($name, $template)
  41. {
  42. $this->templates[(string) $name] = $template;
  43. }
  44. /**
  45. * {@inheritdoc}
  46. */
  47. public function getSource($name)
  48. {
  49. $name = (string) $name;
  50. if (!isset($this->templates[$name])) {
  51. throw new Twig_Error_Loader(sprintf('Template "%s" is not defined.', $name));
  52. }
  53. return $this->templates[$name];
  54. }
  55. /**
  56. * {@inheritdoc}
  57. */
  58. public function exists($name)
  59. {
  60. return isset($this->templates[(string) $name]);
  61. }
  62. /**
  63. * {@inheritdoc}
  64. */
  65. public function getCacheKey($name)
  66. {
  67. $name = (string) $name;
  68. if (!isset($this->templates[$name])) {
  69. throw new Twig_Error_Loader(sprintf('Template "%s" is not defined.', $name));
  70. }
  71. return $this->templates[$name];
  72. }
  73. /**
  74. * {@inheritdoc}
  75. */
  76. public function isFresh($name, $time)
  77. {
  78. $name = (string) $name;
  79. if (!isset($this->templates[$name])) {
  80. throw new Twig_Error_Loader(sprintf('Template "%s" is not defined.', $name));
  81. }
  82. return true;
  83. }
  84. }