1: <?php
2:
3: namespace Charcoal\View;
4:
5: // PSR-7 (http-messaging) dependencies
6: use Psr\Http\Message\ResponseInterface;
7:
8: // Local namespace dependencies
9: use \Charcoal\View\ViewInterface;
10:
11: /**
12: * Provides a PSR-7 renderer that uses a Charcoal View.
13: *
14: * A "PSR-7" renderer is a service that renders a template identifier inside a HTTP Response
15: *
16: * ## Dependencies
17: * - `view` A "Charcoal View", which is any class that implements `\Charcoal\View\ViewInterface`.
18: */
19: class Renderer
20: {
21: /**
22: * @var ViewInterface
23: */
24: private $view;
25:
26: /**
27: * @param array $data The constructor dependencies.
28: */
29: public function __construct(array $data)
30: {
31: $this->setView($data['view']);
32: }
33:
34: /**
35: * @param ViewInterface $view The view instance to use.
36: * @return Renderer Chainable
37: */
38: private function setView(ViewInterface $view)
39: {
40: $this->view = $view;
41: return $this;
42: }
43:
44: /**
45: * @param ResponseInterface $response The HTTP response.
46: * @param string $templateIdent The template identifier to load and render.
47: * @param mixed $context The view controller / context.
48: * @return ResponseInterface
49: */
50: public function render(ResponseInterface $response, $templateIdent, $context = null)
51: {
52: $rendered = $this->view->renderTemplate($templateIdent, $context);
53: $response->getBody()->write($rendered);
54: return $response;
55: }
56: }
57: