Skip to content

Commit ad44c69

Browse files
committed
Update for 2.1 Ref #16
1 parent a4dcd7e commit ad44c69

1 file changed

Lines changed: 39 additions & 13 deletions

File tree

src/PhpRenderer.php

Lines changed: 39 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@
1111
use Psr\Http\Message\ResponseInterface;
1212

1313
/**
14-
* Php View
14+
* Class PhpRenderer
15+
* @package Slim\Views
1516
*
1617
* Render PHP view scripts into a PSR-7 Response object
1718
*/
@@ -39,8 +40,8 @@ public function __construct($templatePath = "")
3940
*
4041
* throws RuntimeException if $templatePath . $template does not exist
4142
*
42-
* @param \ResponseInterface $response
43-
* @param $template
43+
* @param ResponseInterface $response
44+
* @param string $template
4445
* @param array $data
4546
*
4647
* @return ResponseInterface
@@ -50,6 +51,29 @@ public function __construct($templatePath = "")
5051
*/
5152
public function render(ResponseInterface $response, $template, array $data = [])
5253
{
54+
$output = $this->fetch($template, $data);
55+
56+
$response->getBody()->write($output);
57+
58+
return $response;
59+
}
60+
61+
/**
62+
* Renders a template and returns the result as a string
63+
*
64+
* cannot contain template as a key
65+
*
66+
* throws RuntimeException if $templatePath . $template does not exist
67+
*
68+
* @param $template
69+
* @param array $data
70+
*
71+
* @return mixed
72+
*
73+
* @throws \InvalidArgumentException
74+
* @throws \RuntimeException
75+
*/
76+
public function fetch($template, array $data = []) {
5377
if (isset($data['template'])) {
5478
throw new \InvalidArgumentException("Duplicate template key found");
5579
}
@@ -58,17 +82,19 @@ public function render(ResponseInterface $response, $template, array $data = [])
5882
throw new \RuntimeException("View cannot render `$template` because the template does not exist");
5983
}
6084

61-
$render = function ($template, $data) {
62-
extract($data);
63-
include $template;
64-
};
65-
6685
ob_start();
67-
$render($this->templatePath . $template, $data);
68-
$output = ob_get_clean();
86+
$this->protectedIncludeScope($this->templatePath . $template, $data);
87+
$output = ob_get_clean();
6988

70-
$response->getBody()->write($output);
71-
72-
return $response;
89+
return $output;
90+
}
91+
92+
/**
93+
* @param string $template
94+
* @param array $data
95+
*/
96+
protected function protectedIncludeScope ($template, array $data) {
97+
extract($data);
98+
include $template;
7399
}
74100
}

0 commit comments

Comments
 (0)