From e5bc8d5edf02ff27cad4d7304e8aa59a91c934b4 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Mon, 21 Jan 2013 10:26:12 -0800 Subject: [PATCH] Add a CascadingLoader implementation. --- src/Mustache/Loader/CascadingLoader.php | 69 +++++++++++++++++++ .../Test/Loader/CascadingLoaderTest.php | 40 +++++++++++ 2 files changed, 109 insertions(+) create mode 100644 src/Mustache/Loader/CascadingLoader.php create mode 100644 test/Mustache/Test/Loader/CascadingLoaderTest.php diff --git a/src/Mustache/Loader/CascadingLoader.php b/src/Mustache/Loader/CascadingLoader.php new file mode 100644 index 0000000..192edb9 --- /dev/null +++ b/src/Mustache/Loader/CascadingLoader.php @@ -0,0 +1,69 @@ +loaders = array(); + foreach ($loaders as $loader) { + $this->addLoader($loader); + } + } + + /** + * Add a Loader instance. + * + * @param Mustache_Loader $loader A Mustache Loader instance + */ + public function addLoader(Mustache_Loader $loader) + { + $this->loaders[] = $loader; + } + + /** + * Load a Template by name. + * + * @throws Mustache_Exception_UnknownTemplateException If a template file is not found. + * + * @param string $name + * + * @return string Mustache Template source + */ + public function load($name) + { + foreach ($this->loaders as $loader) { + try { + return $loader->load($name); + } catch (Mustache_Exception_UnknownTemplateException $e) { + // do nothing, check the next loader. + } + } + + throw new Mustache_Exception_UnknownTemplateException($name); + } +} diff --git a/test/Mustache/Test/Loader/CascadingLoaderTest.php b/test/Mustache/Test/Loader/CascadingLoaderTest.php new file mode 100644 index 0000000..06e1725 --- /dev/null +++ b/test/Mustache/Test/Loader/CascadingLoaderTest.php @@ -0,0 +1,40 @@ + '{{ foo }}')), + new Mustache_Loader_ArrayLoader(array('bar' => '{{#bar}}BAR{{/bar}}')), + )); + + $this->assertEquals('{{ foo }}', $loader->load('foo')); + $this->assertEquals('{{#bar}}BAR{{/bar}}', $loader->load('bar')); + } + + /** + * @expectedException Mustache_Exception_UnknownTemplateException + */ + public function testMissingTemplatesThrowExceptions() + { + $loader = new Mustache_Loader_CascadingLoader(array( + new Mustache_Loader_ArrayLoader(array('foo' => '{{ foo }}')), + new Mustache_Loader_ArrayLoader(array('bar' => '{{#bar}}BAR{{/bar}}')), + )); + + $loader->load('not_a_real_template'); + } +}