From a048112e2c563c4b841aa85716c672b90f452c08 Mon Sep 17 00:00:00 2001 From: nikic Date: Tue, 3 Apr 2012 23:52:00 +0200 Subject: [PATCH] Add a filesystem template loader. The template loaders loads templates from a base directory (and can optionally use a suffix). For example $templateLoader = new PHPParser_TemplateLoader( $parser, './templates', '.php' ); // loads ./templates/TestTemplate.php $templateLoader->load('TestTemplate'); Again the implementation is not optimal. The loader probably shouldn't intantiate the Template itself, but instead should accept a TemplateFactory. This seemed like overkill to me, so I left it out. --- lib/PHPParser/TemplateLoader.php | 48 +++++++++++++++++++++ test/PHPParser/Tests/TemplateLoaderTest.php | 44 +++++++++++++++++++ 2 files changed, 92 insertions(+) create mode 100644 lib/PHPParser/TemplateLoader.php create mode 100644 test/PHPParser/Tests/TemplateLoaderTest.php diff --git a/lib/PHPParser/TemplateLoader.php b/lib/PHPParser/TemplateLoader.php new file mode 100644 index 0000000..dc9d26d --- /dev/null +++ b/lib/PHPParser/TemplateLoader.php @@ -0,0 +1,48 @@ +parser = $parser; + $this->baseDir = $baseDir; + $this->suffix = $suffix; + } + + /** + * Loads the template with the specified name. + * + * @param string $name The name of template + * + * @return PHPParser_Template The loaded template + */ + public function load($name) { + $file = $this->baseDir . '/' . $name . $this->suffix; + + if (!is_file($file)) { + throw new InvalidArgumentException( + sprintf('The file "%s" does not exist', $file) + ); + } + + return new PHPParser_Template($this->parser, file_get_contents($file)); + } +} \ No newline at end of file diff --git a/test/PHPParser/Tests/TemplateLoaderTest.php b/test/PHPParser/Tests/TemplateLoaderTest.php new file mode 100644 index 0000000..70ca454 --- /dev/null +++ b/test/PHPParser/Tests/TemplateLoaderTest.php @@ -0,0 +1,44 @@ +load('TemplateLoaderTest.php'); + $this->assertInstanceOf('PHPParser_Template', $template); + } + + public function testLoadWithSuffix() { + $templateLoader = new PHPParser_TemplateLoader( + new PHPParser_Parser, dirname(__FILE__), '.php' + ); + + // load this file as a template, as we don't really care about the contents + $template = $templateLoader->load('TemplateLoaderTest'); + $this->assertInstanceOf('PHPParser_Template', $template); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testNonexistentBaseDirectoryError() { + new PHPParser_TemplateLoader( + new PHPParser_Parser, dirname(__FILE__) . '/someDirectoryThatDoesNotExist' + ); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testNonexistentFileError() { + $templateLoader = new PHPParser_TemplateLoader( + new PHPParser_Parser, dirname(__FILE__) + ); + + $templateLoader->load('SomeTemplateThatDoesNotExist'); + } +} \ No newline at end of file