/
PhpEngine.php
555 lines (493 loc) · 14.9 KB
/
PhpEngine.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Templating;
use Symfony\Component\Templating\Storage\Storage;
use Symfony\Component\Templating\Storage\FileStorage;
use Symfony\Component\Templating\Storage\StringStorage;
use Symfony\Component\Templating\Helper\HelperInterface;
use Symfony\Component\Templating\Loader\LoaderInterface;
if (!defined('ENT_SUBSTITUTE')) {
define('ENT_SUBSTITUTE', 8);
}
/**
* PhpEngine is an engine able to render PHP templates.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @api
*/
class PhpEngine implements EngineInterface, \ArrayAccess
{
protected $loader;
protected $current;
protected $helpers;
protected $parents;
protected $stack;
protected $charset;
protected $cache;
protected $escapers;
protected $globals;
protected $parser;
/**
* Constructor.
*
* @param TemplateNameParserInterface $parser A TemplateNameParserInterface instance
* @param LoaderInterface $loader A loader instance
* @param array $helpers An array of helper instances
*/
public function __construct(TemplateNameParserInterface $parser, LoaderInterface $loader, array $helpers = array())
{
$this->parser = $parser;
$this->loader = $loader;
$this->parents = array();
$this->stack = array();
$this->charset = 'UTF-8';
$this->cache = array();
$this->globals = array();
$this->setHelpers($helpers);
$this->initializeEscapers();
foreach ($this->escapers as $context => $escaper) {
$this->setEscaper($context, $escaper);
}
}
/**
* Renders a template.
*
* @param mixed $name A template name or a TemplateReferenceInterface instance
* @param array $parameters An array of parameters to pass to the template
*
* @return string The evaluated template as a string
*
* @throws \InvalidArgumentException if the template does not exist
* @throws \RuntimeException if the template cannot be rendered
*
* @api
*/
public function render($name, array $parameters = array())
{
$storage = $this->load($name);
$key = md5(serialize($storage));
$this->current = $key;
$this->parents[$key] = null;
// attach the global variables
$parameters = array_replace($this->getGlobals(), $parameters);
// render
if (false === $content = $this->evaluate($storage, $parameters)) {
throw new \RuntimeException(sprintf('The template "%s" cannot be rendered.', $this->parser->parse($name)));
}
// decorator
if ($this->parents[$key]) {
$slots = $this->get('slots');
$this->stack[] = $slots->get('_content');
$slots->set('_content', $content);
$content = $this->render($this->parents[$key], $parameters);
$slots->set('_content', array_pop($this->stack));
}
return $content;
}
/**
* Returns true if the template exists.
*
* @param mixed $name A template name or a TemplateReferenceInterface instance
*
* @return Boolean true if the template exists, false otherwise
*
* @api
*/
public function exists($name)
{
try {
$this->load($name);
} catch (\InvalidArgumentException $e) {
return false;
}
return true;
}
/**
* Returns true if this class is able to render the given template.
*
* @param mixed $name A template name or a TemplateReferenceInterface instance
*
* @return Boolean true if this class supports the given resource, false otherwise
*
* @api
*/
public function supports($name)
{
$template = $this->parser->parse($name);
return 'php' === $template->get('engine');
}
/**
* Evaluates a template.
*
* @param Storage $template The template to render
* @param array $parameters An array of parameters to pass to the template
*
* @return string|false The evaluated template, or false if the engine is unable to render the template
*/
protected function evaluate(Storage $template, array $parameters = array())
{
$__template__ = $template;
if (isset($parameters['__template__'])) {
throw new \InvalidArgumentException('Invalid parameter (__template__)');
}
if ($__template__ instanceof FileStorage) {
extract($parameters, EXTR_SKIP);
$view = $this;
ob_start();
require $__template__;
return ob_get_clean();
} elseif ($__template__ instanceof StringStorage) {
extract($parameters, EXTR_SKIP);
$view = $this;
ob_start();
eval('; ?>'.$__template__.'<?php ;');
return ob_get_clean();
}
return false;
}
/**
* Gets a helper value.
*
* @param string $name The helper name
*
* @return mixed The helper value
*
* @throws \InvalidArgumentException if the helper is not defined
*
* @api
*/
public function offsetGet($name)
{
return $this->get($name);
}
/**
* Returns true if the helper is defined.
*
* @param string $name The helper name
*
* @return Boolean true if the helper is defined, false otherwise
*
* @api
*/
public function offsetExists($name)
{
return isset($this->helpers[$name]);
}
/**
* Sets a helper.
*
* @param HelperInterface $name The helper instance
* @param string $value An alias
*
* @api
*/
public function offsetSet($name, $value)
{
$this->set($name, $value);
}
/**
* Removes a helper.
*
* @param string $name The helper name
*
* @api
*/
public function offsetUnset($name)
{
throw new \LogicException(sprintf('You can\'t unset a helper (%s).', $name));
}
/**
* @param Helper[] $helpers An array of helper
*
* @api
*/
public function addHelpers(array $helpers)
{
foreach ($helpers as $alias => $helper) {
$this->set($helper, is_int($alias) ? null : $alias);
}
}
/**
* Sets the helpers.
*
* @param Helper[] $helpers An array of helper
*
* @api
*/
public function setHelpers(array $helpers)
{
$this->helpers = array();
$this->addHelpers($helpers);
}
/**
* Sets a helper.
*
* @param HelperInterface $helper The helper instance
* @param string $alias An alias
*
* @api
*/
public function set(HelperInterface $helper, $alias = null)
{
$this->helpers[$helper->getName()] = $helper;
if (null !== $alias) {
$this->helpers[$alias] = $helper;
}
$helper->setCharset($this->charset);
}
/**
* Returns true if the helper if defined.
*
* @param string $name The helper name
*
* @return Boolean true if the helper is defined, false otherwise
*
* @api
*/
public function has($name)
{
return isset($this->helpers[$name]);
}
/**
* Gets a helper value.
*
* @param string $name The helper name
*
* @return HelperInterface The helper instance
*
* @throws \InvalidArgumentException if the helper is not defined
*
* @api
*/
public function get($name)
{
if (!isset($this->helpers[$name])) {
throw new \InvalidArgumentException(sprintf('The helper "%s" is not defined.', $name));
}
return $this->helpers[$name];
}
/**
* Decorates the current template with another one.
*
* @param string $template The decorator logical name
*
* @api
*/
public function extend($template)
{
$this->parents[$this->current] = $template;
}
/**
* Escapes a string by using the current charset.
*
* @param mixed $value A variable to escape
* @param string $context The context name
*
* @return string The escaped value
*
* @api
*/
public function escape($value, $context = 'html')
{
return call_user_func($this->getEscaper($context), $value);
}
/**
* Sets the charset to use.
*
* @param string $charset The charset
*
* @api
*/
public function setCharset($charset)
{
$this->charset = $charset;
}
/**
* Gets the current charset.
*
* @return string The current charset
*
* @api
*/
public function getCharset()
{
return $this->charset;
}
/**
* Adds an escaper for the given context.
*
* @param string $context The escaper context (html, js, ...)
* @param mixed $escaper A PHP callable
*
* @api
*/
public function setEscaper($context, $escaper)
{
$this->escapers[$context] = $escaper;
}
/**
* Gets an escaper for a given context.
*
* @param string $context The context name
*
* @return mixed $escaper A PHP callable
*
* @api
*/
public function getEscaper($context)
{
if (!isset($this->escapers[$context])) {
throw new \InvalidArgumentException(sprintf('No registered escaper for context "%s".', $context));
}
return $this->escapers[$context];
}
/**
* @param string $name
* @param mixed $value
*
* @api
*/
public function addGlobal($name, $value)
{
$this->globals[$name] = $value;
}
/**
* Returns the assigned globals.
*
* @return array
*
* @api
*/
public function getGlobals()
{
return $this->globals;
}
/**
* Initializes the built-in escapers.
*
* Each function specifies a way for applying a transformation to a string
* passed to it. The purpose is for the string to be "escaped" so it is
* suitable for the format it is being displayed in.
*
* For example, the string: "It's required that you enter a username & password.\n"
* If this were to be displayed as HTML it would be sensible to turn the
* ampersand into '&' and the apostrophe into '&aps;'. However if it were
* going to be used as a string in JavaScript to be displayed in an alert box
* it would be right to leave the string as-is, but c-escape the apostrophe and
* the new line.
*
* For each function there is a define to avoid problems with strings being
* incorrectly specified.
*/
protected function initializeEscapers()
{
$that = $this;
$this->escapers = array(
'html' =>
/**
* Runs the PHP function htmlspecialchars on the value passed.
*
* @param string $value the value to escape
*
* @return string the escaped value
*/
function ($value) use ($that)
{
// Numbers and Boolean values get turned into strings which can cause problems
// with type comparisons (e.g. === or is_int() etc).
return is_string($value) ? htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, $that->getCharset(), false) : $value;
},
'js' =>
/**
* A function that escape all non-alphanumeric characters
* into their \xHH or \uHHHH representations
*
* @param string $value the value to escape
* @return string the escaped value
*/
function ($value) use ($that)
{
if ('UTF-8' != $that->getCharset()) {
$value = $that->convertEncoding($value, 'UTF-8', $that->getCharset());
}
$callback = function ($matches) use ($that)
{
$char = $matches[0];
// \xHH
if (!isset($char[1])) {
return '\\x'.substr('00'.bin2hex($char), -2);
}
// \uHHHH
$char = $that->convertEncoding($char, 'UTF-16BE', 'UTF-8');
return '\\u'.substr('0000'.bin2hex($char), -4);
};
if (null === $value = preg_replace_callback('#[^\p{L}\p{N} ]#u', $callback, $value)) {
throw new \InvalidArgumentException('The string to escape is not a valid UTF-8 string.');
}
if ('UTF-8' != $that->getCharset()) {
$value = $that->convertEncoding($value, $that->getCharset(), 'UTF-8');
}
return $value;
},
);
}
/**
* Convert a string from one encoding to another.
*
* @param string $string The string to convert
* @param string $to The input encoding
* @param string $from The output encoding
*
* @return string The string with the new encoding
*
* @throws \RuntimeException if no suitable encoding function is found (iconv or mbstring)
*/
public function convertEncoding($string, $to, $from)
{
if (function_exists('iconv')) {
return iconv($from, $to, $string);
} elseif (function_exists('mb_convert_encoding')) {
return mb_convert_encoding($string, $to, $from);
}
throw new \RuntimeException('No suitable convert encoding function (use UTF-8 as your encoding or install the iconv or mbstring extension).');
}
/**
* Gets the loader associated with this engine.
*
* @return LoaderInterface A LoaderInterface instance
*/
public function getLoader()
{
return $this->loader;
}
/**
* Loads the given template.
*
* @param mixed $name A template name or a TemplateReferenceInterface instance
*
* @return Storage A Storage instance
*
* @throws \InvalidArgumentException if the template cannot be found
*/
protected function load($name)
{
$template = $this->parser->parse($name);
$key = $template->getLogicalName();
if (isset($this->cache[$key])) {
return $this->cache[$key];
}
$storage = $this->loader->load($template);
if (false === $storage) {
throw new \InvalidArgumentException(sprintf('The template "%s" does not exist.', $template));
}
return $this->cache[$key] = $storage;
}
}