Skip to content

Commit

Permalink
Merge pull request #29 from jeremyVignelles/template-exception
Browse files Browse the repository at this point in the history
Handle exceptions and throwables in templates
  • Loading branch information
akrabat committed Oct 11, 2016
2 parents 2507d39 + dd43c22 commit e6bf98a
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 4 deletions.
16 changes: 12 additions & 4 deletions src/PhpRenderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public function render(ResponseInterface $response, $template, array $data = [])
$output = $this->fetch($template, $data);

$response->getBody()->write($output);

return $response;
}

Expand Down Expand Up @@ -168,9 +168,17 @@ public function fetch($template, array $data = []) {
*/
$data = array_merge($this->attributes, $data);

ob_start();
$this->protectedIncludeScope($this->templatePath . $template, $data);
$output = ob_get_clean();
try {
ob_start();
$this->protectedIncludeScope($this->templatePath . $template, $data);
$output = ob_get_clean();
} catch(\Throwable $e) { // PHP 7+
ob_end_clean();
throw $e;
} catch(\Exception $e) { // PHP < 7
ob_end_clean();
throw $e;
}

return $output;
}
Expand Down
26 changes: 26 additions & 0 deletions tests/PhpRendererTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,32 @@ public function testAttributeMerging() {
$this->assertEquals("Hi", $newResponse->getBody()->getContents());
}

public function testExceptionInTemplate() {
$renderer = new \Slim\Views\PhpRenderer("tests/");

$headers = new Headers();
$body = new Body(fopen('php://temp', 'r+'));
$response = new Response(200, $headers, $body);

try {
$newResponse = $renderer->render($response, "testException.php");
} catch (Throwable $t) { // PHP 7+
// Simulates an error template
$newResponse = $renderer->render($response, "testTemplate.php", [
"hello" => "Hi"
]);
} catch (Exception $e) { // PHP < 7
// Simulates an error template
$newResponse = $renderer->render($response, "testTemplate.php", [
"hello" => "Hi"
]);
}

$newResponse->getBody()->rewind();

$this->assertEquals("Hi", $newResponse->getBody()->getContents());
}

/**
* @expectedException InvalidArgumentException
*/
Expand Down
9 changes: 9 additions & 0 deletions tests/testException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
Hello world. You should not see this because there is an error in the template.
<?php
$exception = new Exception('An error occurred');
if($exception instanceof Throwable) {
echo 2/0;
}

throw $exception;
?>

0 comments on commit e6bf98a

Please sign in to comment.