1: <?php
2:
3: namespace Charcoal\View\Mustache;
4:
5: use InvalidArgumentException;
6: use Traversable;
7:
8:
9: use Mustache_Engine;
10:
11:
12: use Charcoal\View\AbstractEngine;
13:
14: use Charcoal\View\Mustache\HelpersInterface;
15:
16: 17: 18:
19: class MustacheEngine extends AbstractEngine
20: {
21: 22: 23: 24: 25:
26: private $helpers = [];
27:
28: 29: 30: 31: 32:
33: private $mustache;
34:
35: 36: 37:
38: public function type()
39: {
40: return 'mustache';
41: }
42:
43: 44: 45: 46: 47:
48: public function __construct(array $data)
49: {
50: parent::__construct($data);
51:
52: if (isset($data['helpers'])) {
53: $this->setHelpers($data['helpers']);
54: }
55: }
56:
57: 58: 59:
60: protected function mustache()
61: {
62: if ($this->mustache === null) {
63: $this->mustache = $this->createMustache();
64: }
65:
66: return $this->mustache;
67: }
68:
69: 70: 71:
72: protected function createMustache()
73: {
74: $mustache = new Mustache_Engine([
75: 'cache' => '../cache/mustache',
76: 'loader' => $this->loader(),
77: 'partials_loader' => $this->loader(),
78: 'strict_callables' => true,
79: 'helpers' => $this->helpers()
80: ]);
81:
82: return $mustache;
83: }
84:
85: 86: 87: 88: 89: 90: 91:
92: public function setHelpers($helpers)
93: {
94: if ($helpers instanceof HelpersInterface) {
95: $helpers = $helpers->toArray();
96: }
97:
98: if (!is_array($helpers) && !$helpers instanceof Traversable) {
99: throw new InvalidArgumentException(sprintf(
100: 'setHelpers expects an array of helpers, received %s',
101: (is_object($helpers) ? get_class($helpers) : gettype($helpers))
102: ));
103: }
104:
105: $this->helpers = [];
106: foreach ($helpers as $name => $helper) {
107: $this->addHelper($name, $helper);
108: }
109:
110: return $this;
111: }
112:
113: 114: 115: 116: 117: 118: 119:
120: public function mergeHelpers($helpers)
121: {
122: if ($helpers instanceof HelpersInterface) {
123: $helpers = $helpers->toArray();
124: }
125:
126: if (!is_array($helpers) && !$helpers instanceof Traversable) {
127: throw new InvalidArgumentException(sprintf(
128: 'mergeHelpers expects an array of helpers, received %s',
129: (is_object($helpers) ? get_class($helpers) : gettype($helpers))
130: ));
131: }
132:
133: foreach ($helpers as $name => $helper) {
134: $this->addHelper($name, $helper);
135: }
136:
137: return $this;
138: }
139:
140: 141: 142: 143: 144: 145: 146:
147: public function addHelper($name, $helper)
148: {
149: $this->helpers[$name] = $helper;
150:
151: return $this;
152: }
153:
154: 155: 156: 157: 158:
159: public function helpers()
160: {
161: return $this->helpers;
162: }
163:
164: 165: 166: 167: 168:
169: public function render($templateIdent, $context)
170: {
171: return $this->mustache()->render($templateIdent, $context);
172: }
173:
174: 175: 176: 177: 178:
179: public function renderTemplate($templateString, $context)
180: {
181: return $this->mustache()->render($templateString, $context);
182: }
183: }
184: