1: <?php
2:
3: namespace Charcoal\View;
4:
5: // Dependencies from `PHP`
6: use \Exception;
7: use \InvalidArgumentException;
8:
9: // PSR-3 (logger) dependencies
10: use \Psr\Log\LoggerAwareInterface;
11: use \Psr\Log\LoggerAwareTrait;
12:
13: // Local namespace dependencie
14: use \Charcoal\View\EngineInterface;
15: use \Charcoal\View\ViewInterface;
16:
17: /**
18: * Base abstract class for _View_ interfaces, implements `ViewInterface`.
19: *
20: * Also implements the `ConfigurableInterface`
21: */
22: abstract class AbstractView implements
23: LoggerAwareInterface,
24: ViewInterface
25: {
26: use LoggerAwareTrait;
27:
28: /**
29: * @var EngineInterface $engine
30: */
31: private $engine;
32:
33: /**
34: * Build the object with an array of dependencies.
35: *
36: * ## Parameters:
37: * - `logger` a PSR-3 logger
38: *
39: * @param array $data View class dependencies.
40: * @throws InvalidArgumentException If required parameters are missing.
41: */
42: public function __construct(array $data)
43: {
44: $this->setLogger($data['logger']);
45: $this->setEngine($data['engine']);
46: }
47:
48: /**
49: * Set the engine (`EngineInterface`) dependency.
50: *
51: * @param EngineInterface $engine The rendering engine.
52: * @return void
53: */
54: private function setEngine(EngineInterface $engine)
55: {
56: $this->engine = $engine;
57: }
58:
59: /**
60: * Get the view's rendering engine instance.
61: *
62: * @return EngineInterface
63: */
64: protected function engine()
65: {
66: return $this->engine;
67: }
68:
69:
70: /**
71: * Load a template (from identifier).
72: *
73: * @param string $templateIdent The template identifier to load..
74: * @throws InvalidArgumentException If the template ident is not a string.
75: * @return string
76: */
77: public function loadTemplate($templateIdent)
78: {
79: if (!is_string($templateIdent)) {
80: throw new InvalidArgumentException(
81: 'Template ident must be a string'
82: );
83: }
84: if (!$templateIdent) {
85: return '';
86: }
87: return $this->engine()->loadTemplate($templateIdent);
88: }
89:
90: /**
91: * Load a template (from identifier) and render it.
92: *
93: * @param string $templateIdent The template identifier, to load and render.
94: * @param mixed $context The view controller (rendering context).
95: * @return string
96: */
97: public function render($templateIdent, $context = null)
98: {
99: return $this->engine()->render($templateIdent, $context);
100: }
101:
102: /**
103: * Render a template (from string).
104: *
105: * @param string $templateString The full template string to render.
106: * @param mixed $context The view controller (rendering context).
107: * @return string
108: */
109: public function renderTemplate($templateString, $context = null)
110: {
111: return $this->engine()->render($templateString, $context);
112: }
113: }
114: