Skip to content

Commit e6bf98a

Browse files
authored
Merge pull request #29 from jeremyVignelles/template-exception
Handle exceptions and throwables in templates
2 parents 2507d39 + dd43c22 commit e6bf98a

3 files changed

Lines changed: 47 additions & 4 deletions

File tree

src/PhpRenderer.php

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ public function render(ResponseInterface $response, $template, array $data = [])
6666
$output = $this->fetch($template, $data);
6767

6868
$response->getBody()->write($output);
69-
69+
7070
return $response;
7171
}
7272

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

171-
ob_start();
172-
$this->protectedIncludeScope($this->templatePath . $template, $data);
173-
$output = ob_get_clean();
171+
try {
172+
ob_start();
173+
$this->protectedIncludeScope($this->templatePath . $template, $data);
174+
$output = ob_get_clean();
175+
} catch(\Throwable $e) { // PHP 7+
176+
ob_end_clean();
177+
throw $e;
178+
} catch(\Exception $e) { // PHP < 7
179+
ob_end_clean();
180+
throw $e;
181+
}
174182

175183
return $output;
176184
}

tests/PhpRendererTest.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,32 @@ public function testAttributeMerging() {
5757
$this->assertEquals("Hi", $newResponse->getBody()->getContents());
5858
}
5959

60+
public function testExceptionInTemplate() {
61+
$renderer = new \Slim\Views\PhpRenderer("tests/");
62+
63+
$headers = new Headers();
64+
$body = new Body(fopen('php://temp', 'r+'));
65+
$response = new Response(200, $headers, $body);
66+
67+
try {
68+
$newResponse = $renderer->render($response, "testException.php");
69+
} catch (Throwable $t) { // PHP 7+
70+
// Simulates an error template
71+
$newResponse = $renderer->render($response, "testTemplate.php", [
72+
"hello" => "Hi"
73+
]);
74+
} catch (Exception $e) { // PHP < 7
75+
// Simulates an error template
76+
$newResponse = $renderer->render($response, "testTemplate.php", [
77+
"hello" => "Hi"
78+
]);
79+
}
80+
81+
$newResponse->getBody()->rewind();
82+
83+
$this->assertEquals("Hi", $newResponse->getBody()->getContents());
84+
}
85+
6086
/**
6187
* @expectedException InvalidArgumentException
6288
*/

tests/testException.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
Hello world. You should not see this because there is an error in the template.
2+
<?php
3+
$exception = new Exception('An error occurred');
4+
if($exception instanceof Throwable) {
5+
echo 2/0;
6+
}
7+
8+
throw $exception;
9+
?>

0 commit comments

Comments
 (0)