This repository has been archived by the owner on Jan 31, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 61
/
PhpRenderer.php
581 lines (527 loc) · 18.2 KB
/
PhpRenderer.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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\View\Renderer;
use ArrayAccess;
use Traversable;
use Zend\Filter\FilterChain;
use Zend\ServiceManager\ServiceManager;
use Zend\View\Exception;
use Zend\View\HelperPluginManager;
use Zend\View\Helper\AbstractHelper;
use Zend\View\Model\ModelInterface as Model;
use Zend\View\Renderer\RendererInterface as Renderer;
use Zend\View\Resolver\ResolverInterface as Resolver;
use Zend\View\Resolver\TemplatePathStack;
use Zend\View\Variables;
// @codingStandardsIgnoreStart
/**
* Class for Zend\View\Strategy\PhpRendererStrategy to help enforce private constructs.
*
* Note: all private variables in this class are prefixed with "__". This is to
* mark them as part of the internal implementation, and thus prevent conflict
* with variables injected into the renderer.
*
* Convenience methods for build in helpers (@see __call):
*
* @method string asset($asset)
* @method string|null basePath($file = null)
* @method \Zend\View\Helper\Cycle cycle(array $data = array(), $name = \Zend\View\Helper\Cycle::DEFAULT_NAME)
* @method \Zend\View\Helper\DeclareVars declareVars()
* @method \Zend\View\Helper\Doctype doctype($doctype = null)
* @method mixed escapeCss($value, $recurse = \Zend\View\Helper\Escaper\AbstractHelper::RECURSE_NONE)
* @method mixed escapeHtml($value, $recurse = \Zend\View\Helper\Escaper\AbstractHelper::RECURSE_NONE)
* @method mixed escapeHtmlAttr($value, $recurse = \Zend\View\Helper\Escaper\AbstractHelper::RECURSE_NONE)
* @method mixed escapeJs($value, $recurse = \Zend\View\Helper\Escaper\AbstractHelper::RECURSE_NONE)
* @method mixed escapeUrl($value, $recurse = \Zend\View\Helper\Escaper\AbstractHelper::RECURSE_NONE)
* @method \Zend\View\Helper\FlashMessenger flashMessenger($namespace = null)
* @method \Zend\View\Helper\Gravatar gravatar($email = "", $options = array(), $attribs = array())
* @method \Zend\View\Helper\HeadLink headLink(array $attributes = null, $placement = \Zend\View\Helper\Placeholder\Container\AbstractContainer::APPEND)
* @method \Zend\View\Helper\HeadMeta headMeta($content = null, $keyValue = null, $keyType = 'name', $modifiers = array(), $placement = \Zend\View\Helper\Placeholder\Container\AbstractContainer::APPEND)
* @method \Zend\View\Helper\HeadScript headScript($mode = \Zend\View\Helper\HeadScript::FILE, $spec = null, $placement = 'APPEND', array $attrs = array(), $type = 'text/javascript')
* @method \Zend\View\Helper\HeadStyle headStyle($content = null, $placement = 'APPEND', $attributes = array())
* @method \Zend\View\Helper\HeadTitle headTitle($title = null, $setType = null)
* @method string htmlFlash($data, array $attribs = array(), array $params = array(), $content = null)
* @method string htmlList(array $items, $ordered = false, $attribs = false, $escape = true)
* @method string htmlObject($data = null, $type = null, array $attribs = array(), array $params = array(), $content = null)
* @method string htmlPage($data, array $attribs = array(), array $params = array(), $content = null)
* @method string htmlQuicktime($data, array $attribs = array(), array $params = array(), $content = null)
* @method mixed|null identity()
* @method \Zend\View\Helper\InlineScript inlineScript($mode = \Zend\View\Helper\HeadScript::FILE, $spec = null, $placement = 'APPEND', array $attrs = array(), $type = 'text/javascript')
* @method string|void json($data, array $jsonOptions = array())
* @method \Zend\View\Helper\Layout layout($template = null)
* @method \Zend\View\Helper\Navigation navigation($container = null)
* @method string paginationControl(\Zend\Paginator\Paginator $paginator = null, $scrollingStyle = null, $partial = null, $params = null)
* @method string|\Zend\View\Helper\Partial partial($name = null, $values = null)
* @method string partialLoop($name = null, $values = null)
* @method \Zend\View\Helper\Placeholder\Container\AbstractContainer placeholder($name = null)
* @method string renderChildModel($child)
* @method void renderToPlaceholder($script, $placeholder)
* @method string serverUrl($requestUri = null)
* @method string url($name = null, array $params = array(), $options = array(), $reuseMatchedParams = false)
* @method \Zend\View\Helper\ViewModel viewModel()
* @method \Zend\View\Helper\Navigation\Breadcrumbs breadCrumbs($container = null)
* @method \Zend\View\Helper\Navigation\Links links($container = null)
* @method \Zend\View\Helper\Navigation\Menu menu($container = null)
* @method \Zend\View\Helper\Navigation\Sitemap sitemap($container = null)
*/
class PhpRenderer implements Renderer, TreeRendererInterface
{
/**
* @var string Rendered content
*/
private $__content = '';
/**
* @var bool Whether or not to render trees of view models
*/
private $__renderTrees = false;
/**
* Template being rendered
*
* @var null|string
*/
private $__template = null;
/**
* Queue of templates to render
* @var array
*/
private $__templates = [];
/**
* Template resolver
*
* @var Resolver
*/
private $__templateResolver;
/**
* Script file name to execute
*
* @var string
*/
private $__file = null;
/**
* Helper plugin manager
*
* @var HelperPluginManager
*/
private $__helpers;
/**
* @var FilterChain
*/
private $__filterChain;
/**
* @var ArrayAccess|array ArrayAccess or associative array representing available variables
*/
private $__vars;
/**
* @var array Temporary variable stack; used when variables passed to render()
*/
private $__varsCache = [];
// @codingStandardsIgnoreEnd
/**
* Constructor.
*
*
* @todo handle passing helper plugin manager, options
* @todo handle passing filter chain, options
* @todo handle passing variables object, options
* @todo handle passing resolver object, options
* @param array $config Configuration key-value pairs.
*/
public function __construct($config = [])
{
$this->init();
}
/**
* Return the template engine object
*
* Returns the object instance, as it is its own template engine
*
* @return PhpRenderer
*/
public function getEngine()
{
return $this;
}
/**
* Allow custom object initialization when extending PhpRenderer
*
* Triggered by {@link __construct() the constructor} as its final action.
*
* @return void
*/
public function init()
{
}
/**
* Set script resolver
*
* @param Resolver $resolver
* @return PhpRenderer
* @throws Exception\InvalidArgumentException
*/
public function setResolver(Resolver $resolver)
{
$this->__templateResolver = $resolver;
return $this;
}
/**
* Retrieve template name or template resolver
*
* @param null|string $name
* @return string|Resolver
*/
public function resolver($name = null)
{
if (null === $this->__templateResolver) {
$this->setResolver(new TemplatePathStack());
}
if (null !== $name) {
return $this->__templateResolver->resolve($name, $this);
}
return $this->__templateResolver;
}
/**
* Set variable storage
*
* Expects either an array, or an object implementing ArrayAccess.
*
* @param array|ArrayAccess $variables
* @return PhpRenderer
* @throws Exception\InvalidArgumentException
*/
public function setVars($variables)
{
if (! is_array($variables) && ! $variables instanceof ArrayAccess) {
throw new Exception\InvalidArgumentException(sprintf(
'Expected array or ArrayAccess object; received "%s"',
(is_object($variables) ? get_class($variables) : gettype($variables))
));
}
// Enforce a Variables container
if (! $variables instanceof Variables) {
$variablesAsArray = [];
foreach ($variables as $key => $value) {
$variablesAsArray[$key] = $value;
}
$variables = new Variables($variablesAsArray);
}
$this->__vars = $variables;
return $this;
}
/**
* Get a single variable, or all variables
*
* @param mixed $key
* @return mixed
*/
public function vars($key = null)
{
if (null === $this->__vars) {
$this->setVars(new Variables());
}
if (null === $key) {
return $this->__vars;
}
return $this->__vars[$key];
}
/**
* Get a single variable
*
* @param mixed $key
* @return mixed
*/
public function get($key)
{
if (null === $this->__vars) {
$this->setVars(new Variables());
}
return $this->__vars[$key];
}
/**
* Overloading: proxy to Variables container
*
* @param string $name
* @return mixed
*/
public function __get($name)
{
$vars = $this->vars();
return $vars[$name];
}
/**
* Overloading: proxy to Variables container
*
* @param string $name
* @param mixed $value
* @return void
*/
public function __set($name, $value)
{
$vars = $this->vars();
$vars[$name] = $value;
}
/**
* Overloading: proxy to Variables container
*
* @param string $name
* @return bool
*/
public function __isset($name)
{
$vars = $this->vars();
return isset($vars[$name]);
}
/**
* Overloading: proxy to Variables container
*
* @param string $name
* @return void
*/
public function __unset($name)
{
$vars = $this->vars();
if (! isset($vars[$name])) {
return;
}
unset($vars[$name]);
}
/**
* Set helper plugin manager instance
*
* @param string|HelperPluginManager $helpers
* @return PhpRenderer
* @throws Exception\InvalidArgumentException
*/
public function setHelperPluginManager($helpers)
{
if (is_string($helpers)) {
if (! class_exists($helpers)) {
throw new Exception\InvalidArgumentException(sprintf(
'Invalid helper helpers class provided (%s)',
$helpers
));
}
$helpers = new $helpers(new ServiceManager());
}
if (! $helpers instanceof HelperPluginManager) {
throw new Exception\InvalidArgumentException(sprintf(
'Helper helpers must extend Zend\View\HelperPluginManager; got type "%s" instead',
(is_object($helpers) ? get_class($helpers) : gettype($helpers))
));
}
$helpers->setRenderer($this);
$this->__helpers = $helpers;
return $this;
}
/**
* Get helper plugin manager instance
*
* @return HelperPluginManager
*/
public function getHelperPluginManager()
{
if (null === $this->__helpers) {
$this->setHelperPluginManager(new HelperPluginManager(new ServiceManager()));
}
return $this->__helpers;
}
/**
* Get plugin instance
*
* @param string $name Name of plugin to return
* @param null|array $options Options to pass to plugin constructor (if not already instantiated)
* @return AbstractHelper
*/
public function plugin($name, array $options = null)
{
return $this->getHelperPluginManager()->get($name, $options);
}
/**
* Overloading: proxy to helpers
*
* Proxies to the attached plugin manager to retrieve, return, and potentially
* execute helpers.
*
* * If the helper does not define __invoke, it will be returned
* * If the helper does define __invoke, it will be called as a functor
*
* @param string $method
* @param array $argv
* @return mixed
*/
public function __call($method, $argv)
{
$plugin = $this->plugin($method);
if (is_callable($plugin)) {
return call_user_func_array($plugin, $argv);
}
return $plugin;
}
/**
* Set filter chain
*
* @param FilterChain $filters
* @return PhpRenderer
*/
public function setFilterChain(FilterChain $filters)
{
$this->__filterChain = $filters;
return $this;
}
/**
* Retrieve filter chain for post-filtering script content
*
* @return FilterChain
*/
public function getFilterChain()
{
if (null === $this->__filterChain) {
$this->setFilterChain(new FilterChain());
}
return $this->__filterChain;
}
/**
* Processes a view script and returns the output.
*
* @param string|Model $nameOrModel Either the template to use, or a
* ViewModel. The ViewModel must have the
* template as an option in order to be
* valid.
* @param null|array|Traversable $values Values to use when rendering. If none
* provided, uses those in the composed
* variables container.
* @return string The script output.
* @throws Exception\DomainException if a ViewModel is passed, but does not
* contain a template option.
* @throws Exception\InvalidArgumentException if the values passed are not
* an array or ArrayAccess object
* @throws Exception\RuntimeException if the template cannot be rendered
*/
public function render($nameOrModel, $values = null)
{
if ($nameOrModel instanceof Model) {
$model = $nameOrModel;
$nameOrModel = $model->getTemplate();
if (empty($nameOrModel)) {
throw new Exception\DomainException(sprintf(
'%s: received View Model argument, but template is empty',
__METHOD__
));
}
$options = $model->getOptions();
foreach ($options as $setting => $value) {
$method = 'set' . $setting;
if (method_exists($this, $method)) {
$this->$method($value);
}
unset($method, $setting, $value);
}
unset($options);
// Give view model awareness via ViewModel helper
$helper = $this->plugin('view_model');
$helper->setCurrent($model);
$values = $model->getVariables();
unset($model);
}
// find the script file name using the parent private method
$this->addTemplate($nameOrModel);
unset($nameOrModel); // remove $name from local scope
$this->__varsCache[] = $this->vars();
if (null !== $values) {
$this->setVars($values);
}
unset($values);
// extract all assigned vars (pre-escaped), but not 'this'.
// assigns to a double-underscored variable, to prevent naming collisions
$__vars = $this->vars()->getArrayCopy();
if (array_key_exists('this', $__vars)) {
unset($__vars['this']);
}
extract($__vars);
unset($__vars); // remove $__vars from local scope
$this->__content = '';
while ($this->__template = array_pop($this->__templates)) {
$this->__file = $this->resolver($this->__template);
if (! $this->__file) {
throw new Exception\RuntimeException(sprintf(
'%s: Unable to render template "%s"; resolver could not resolve to a file',
__METHOD__,
$this->__template
));
}
try {
ob_start();
$includeReturn = include $this->__file;
$this->__content = ob_get_clean();
} catch (\Throwable $ex) {
ob_end_clean();
throw $ex;
} catch (\Exception $ex) { // @TODO clean up once PHP 7 requirement is enforced
ob_end_clean();
throw $ex;
}
if ($includeReturn === false && empty($this->__content)) {
throw new Exception\UnexpectedValueException(sprintf(
'%s: Unable to render template "%s"; file include failed',
__METHOD__,
$this->__file
));
}
}
$this->setVars(array_pop($this->__varsCache));
if ($this->__filterChain instanceof FilterChain) {
return $this->__filterChain->filter($this->__content); // filter output
}
return $this->__content;
}
/**
* Set flag indicating whether or not we should render trees of view models
*
* If set to true, the View instance will not attempt to render children
* separately, but instead pass the root view model directly to the PhpRenderer.
* It is then up to the developer to render the children from within the
* view script.
*
* @param bool $renderTrees
* @return PhpRenderer
*/
public function setCanRenderTrees($renderTrees)
{
$this->__renderTrees = (bool) $renderTrees;
return $this;
}
/**
* Can we render trees, or are we configured to do so?
*
* @return bool
*/
public function canRenderTrees()
{
return $this->__renderTrees;
}
/**
* Add a template to the stack
*
* @param string $template
* @return PhpRenderer
*/
public function addTemplate($template)
{
$this->__templates[] = $template;
return $this;
}
/**
* Make sure View variables are cloned when the view is cloned.
*
* @return PhpRenderer
*/
public function __clone()
{
$this->__vars = clone $this->vars();
}
}