/
TwigView.php
352 lines (306 loc) · 9.91 KB
/
TwigView.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* Copyright (c) 2014 Cees-Jan Kiewiet
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 1.0.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\TwigView\View;
use Cake\Core\Configure;
use Cake\Core\Plugin;
use Cake\TwigView\Panel\TwigPanel;
use Cake\TwigView\Twig\Extension;
use Cake\TwigView\Twig\FileLoader;
use Cake\TwigView\Twig\TokenParser;
use Cake\View\Exception\MissingLayoutException;
use Cake\View\Exception\MissingTemplateException;
use Cake\View\View;
use Jasny\Twig\ArrayExtension;
use Jasny\Twig\DateExtension;
use Jasny\Twig\PcreExtension;
use Jasny\Twig\TextExtension;
use RuntimeException;
use Twig\Environment;
use Twig\Extension\DebugExtension;
use Twig\Extension\StringLoaderExtension;
use Twig\Extra\Markdown\DefaultMarkdown;
use Twig\Extra\Markdown\MarkdownExtension;
use Twig\Extra\Markdown\MarkdownInterface;
use Twig\Extra\Markdown\MarkdownRuntime;
use Twig\Loader\LoaderInterface;
use Twig\Profiler\Profile;
use Twig\RuntimeLoader\RuntimeLoaderInterface;
/**
* Class TwigView.
*/
class TwigView extends View
{
/**
* @var \Twig\Environment|null
*/
protected static $twig;
/**
* @var \Twig\Profiler\Profile|null
*/
protected static $profile;
/**
* Default config options.
*
* Use ViewBuilder::setOption()/setOptions() in your controller to set these options.
*
* - `environment` - Array of config you would pass into \Twig\Environment to overwrite the default settings.
* See http://twig.sensiolabs.org/doc/api.html#environment-options.
* - `markdown` - Set to 'default' to use `DefaultMarkdown` or
* provide custom Twig\Extra\Markdown\MarkdownInterface instance.
* See https://twig.symfony.com/doc/3.x/filters/markdown_to_html.html.
*
* @var array
*/
protected $_defaultConfig = [
'environment' => [
],
'markdown' => null,
];
/**
* @inheritDoc
*/
protected $_ext = '.twig';
/**
* List of extensions searched when loading templates.
*
* @var string[]
*/
protected $extensions = [
'.twig',
];
/**
* Initialize view.
*
* @return void
*/
public function initialize(): void
{
parent::initialize();
if (static::$twig === null) {
// Cache instance to avoid re-creating when rendering Cells
static::$twig = $this->createEnvironment();
$this->initializeTokenParser();
$this->initializeExtensions();
if (Configure::read('debug') && Plugin::isLoaded('DebugKit')) {
$this->initializeProfiler();
}
}
if (Configure::read('debug') && Plugin::isLoaded('DebugKit')) {
TwigPanel::setExtensions($this->extensions);
}
}
/**
* Get Twig Environment instance.
*
* @return \Twig\Environment
*/
public function getTwig(): Environment
{
if (static::$twig === null) {
throw new RuntimeException('Twig Environment instance not created.');
}
return static::$twig;
}
/**
* Gets Twig Profile if profiler enabled.
*
* @return \Twig\Profiler\Profile|null
*/
public function getProfile(): ?Profile
{
return static::$profile;
}
/** Gets the template file extensions.
*
* @return string[]
*/
public function getExtensions(): array
{
return $this->extensions;
}
/**
* Creates the Twig LoaderInterface instance.
*
* @return \Twig\Loader\LoaderInterface
*/
protected function createLoader(): LoaderInterface
{
return new FileLoader($this->extensions);
}
/**
* Creates the Twig Environment.
*
* @return \Twig\Environment
*/
protected function createEnvironment(): Environment
{
$debug = Configure::read('debug', false);
$cachePath = CACHE . 'twig_view' . DS;
$config = $this->getConfig('environment') + [
'charset' => Configure::read('App.encoding', 'UTF-8'),
'debug' => $debug,
'cache' => $debug ? false : $cachePath,
'strict_variables' => $debug,
];
if ($config['cache'] === true) {
$config['cache'] = $cachePath;
}
$env = new Environment($this->createLoader(), $config);
// Must add before any templates are rendered so can be updated in _render().
$env->addGlobal('_view', $this);
return $env;
}
/**
* Adds custom Twig token parsers.
*
* @return void
*/
protected function initializeTokenParser(): void
{
$this->getTwig()->addTokenParser(new TokenParser\CellParser());
$this->getTwig()->addTokenParser(new TokenParser\ElementParser());
}
// phpcs:disable CakePHP.Commenting.FunctionComment.InvalidReturnVoid
/**
* Adds Twig extensions.
*
* @return void
*/
protected function initializeExtensions(): void
{
$twig = $this->getTwig();
// Twig core extensions
$twig->addExtension(new StringLoaderExtension());
if (Configure::read('debug', false)) {
$twig->addExtension(new DebugExtension());
}
// CakePHP bridging extensions
$twig->addExtension(new Extension\ArraysExtension());
$twig->addExtension(new Extension\BasicExtension());
$twig->addExtension(new Extension\ConfigureExtension());
$twig->addExtension(new Extension\I18nExtension());
$twig->addExtension(new Extension\InflectorExtension());
$twig->addExtension(new Extension\NumberExtension());
$twig->addExtension(new Extension\StringsExtension());
$twig->addExtension(new Extension\TimeExtension());
$twig->addExtension(new Extension\UtilsExtension());
$twig->addExtension(new Extension\ViewExtension());
// Markdown extension
$markdown = $this->getConfig('markdown');
if ($markdown !== null) {
$twig->addExtension(new MarkdownExtension());
$engine = $markdown === 'default' ? new DefaultMarkdown() : $markdown;
$twig->addRuntimeLoader(new class ($engine) implements RuntimeLoaderInterface {
/**
* @var \Twig\Extra\Markdown\MarkdownInterface
*/
private $engine;
/**
* @param \Twig\Extra\Markdown\MarkdownInterface $engine MarkdownInterface instance
*/
public function __construct(MarkdownInterface $engine)
{
$this->engine = $engine;
}
/**
* @param string $class FQCN
* @return object|null
*/
public function load($class)
{
if ($class === MarkdownRuntime::class) {
return new MarkdownRuntime($this->engine);
}
return null;
}
});
}
// jasny/twig-extensions
$twig->addExtension(new DateExtension());
$twig->addExtension(new ArrayExtension());
$twig->addExtension(new PcreExtension());
$twig->addExtension(new TextExtension());
}
// phpcs:enable
/**
* Initializes Twig profiler extension.
*
* @return void
*/
protected function initializeProfiler(): void
{
static::$profile = new Profile();
$this->getTwig()->addExtension(new Extension\ProfilerExtension(static::$profile));
}
/**
* @inheritDoc
*/
protected function _evaluate(string $templateFile, array $dataForView): string
{
// Set _view for each render because Twig Environment is shared between views.
$this->getTwig()->addGlobal('_view', $this);
$dataForView = array_merge(
$dataForView,
iterator_to_array($this->helpers()->getIterator())
);
return $this->getTwig()->load($templateFile)->render($dataForView);
}
/**
* @inheritDoc
*/
protected function _getTemplateFileName(?string $name = null): string
{
foreach ($this->extensions as $extension) {
$this->_ext = $extension;
try {
return parent::_getTemplateFileName($name);
} catch (MissingTemplateException $exception) {
$missingException = $exception;
}
}
throw $missingException ?? new MissingTemplateException($name ?? $this->getTemplate());
}
/**
* @inheritDoc
*/
protected function _getLayoutFileName(?string $name = null): string
{
foreach ($this->extensions as $extension) {
$this->_ext = $extension;
try {
return parent::_getLayoutFileName($name);
} catch (MissingLayoutException $exception) {
$missingException = $exception;
}
}
throw $missingException ?? new MissingLayoutException($name ?? $this->getLayout());
}
/**
* @inheritDoc
*/
protected function _getElementFileName(string $name, bool $pluginCheck = true)
{
foreach ($this->extensions as $extension) {
$this->_ext = $extension;
$result = parent::_getElementFileName($name, $pluginCheck);
if ($result !== false) {
return $result;
}
}
return false;
}
}