-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathComponentRenderer.php
680 lines (605 loc) · 24.7 KB
/
ComponentRenderer.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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
<?php
namespace SMS\FluidComponents\Fluid\ViewHelper;
use Psr\Container\ContainerInterface;
use SMS\FluidComponents\Domain\Model\RequiredSlotPlaceholder;
use SMS\FluidComponents\Domain\Model\Slot;
use SMS\FluidComponents\Interfaces\ComponentAware;
use SMS\FluidComponents\Interfaces\EscapedParameter;
use SMS\FluidComponents\Interfaces\RenderingContextAware;
use SMS\FluidComponents\Utility\ComponentArgumentConverter;
use SMS\FluidComponents\Utility\ComponentLoader;
use SMS\FluidComponents\Utility\ComponentPrefixer\ComponentPrefixerInterface;
use SMS\FluidComponents\Utility\ComponentPrefixer\GenericComponentPrefixer;
use SMS\FluidComponents\Utility\ComponentSettings;
use SMS\FluidComponents\ViewHelpers\ComponentViewHelper;
use SMS\FluidComponents\ViewHelpers\ContentViewHelper;
use SMS\FluidComponents\ViewHelpers\ParamViewHelper;
use TYPO3\CMS\Core\Configuration\Features;
use TYPO3\CMS\Core\Information\Typo3Version;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Fluid\Core\Rendering\RenderingContext;
use TYPO3\CMS\Fluid\Core\Rendering\RenderingContextFactory;
use TYPO3Fluid\Fluid\Core\Compiler\TemplateCompiler;
use TYPO3Fluid\Fluid\Core\Parser\SyntaxTree\BooleanNode;
use TYPO3Fluid\Fluid\Core\Parser\SyntaxTree\EscapingNode;
use TYPO3Fluid\Fluid\Core\Parser\SyntaxTree\NodeInterface;
use TYPO3Fluid\Fluid\Core\Parser\SyntaxTree\ViewHelperNode;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;
use TYPO3Fluid\Fluid\Core\ViewHelper\ArgumentDefinition;
use TYPO3Fluid\Fluid\Core\ViewHelper\Exception;
class ComponentRenderer extends AbstractViewHelper
{
const DEFAULT_SLOT = 'content';
protected $reservedArguments = [
'class',
'component',
self::DEFAULT_SLOT,
'settings',
];
/**
* Namespace of the component the viewhelper should render
*
* @var string
*/
protected $componentNamespace;
/**
* Cache for component template instance used for rendering
*
* @var \TYPO3Fluid\Fluid\Core\Parser\ParsedTemplateInterface
*/
protected $parsedTemplate;
/**
* Cache of component argument definitions; the key is the component namespace, and the
* value is the array of argument definitions.
*
* In our benchmarks, this cache leads to a 40% improvement when using a certain
* ViewHelper class many times throughout the rendering process.
* @var array
*/
protected static $componentArgumentDefinitionCache = [];
/**
* Cache of component prefixer objects
*
* @var array
*/
protected static $componentPrefixerCache = [];
/**
* Components are HTML markup which should not be escaped
*
* @var boolean
*/
protected $escapeOutput = false;
/**
* Children should be treated just like an argument
*
* @var boolean
*/
protected $escapeChildren = true;
/**
* @var ComponentLoader
*/
protected ComponentLoader $componentLoader;
/**
* @var ComponentSettings
*/
protected ComponentSettings $componentSettings;
/**
* @var ComponentArgumentConverter
*/
protected ComponentArgumentConverter $componentArgumentConverter;
/**
* @var ContainerInterface
*/
protected ContainerInterface $container;
/**
* @param ComponentLoader $componentLoader
* @param ComponentSettings $componentSettings
* @param ComponentArgumentConverter $componentArgumentConverter
* @param ContainerInterface $container
*/
public function __construct(
ComponentLoader $componentLoader,
ComponentSettings $componentSettings,
ComponentArgumentConverter $componentArgumentConverter,
ContainerInterface $container
) {
$this->componentLoader = $componentLoader;
$this->componentSettings = $componentSettings;
$this->componentArgumentConverter = $componentArgumentConverter;
$this->container = $container;
}
/**
* Sets the namespace of the component the viewhelper should render
*
* @param string $componentNamespace
* @return self
*/
public function setComponentNamespace($componentNamespace)
{
$this->componentNamespace = $componentNamespace;
return $this;
}
/**
* Returns the namespace of the component the viewhelper renders
*
* @return void
*/
public function getComponentNamespace()
{
return $this->componentNamespace;
}
/**
* Returns the component prefix
*
* @return string
*/
public function getComponentClass()
{
return $this->getComponentPrefixer()->prefix($this->componentNamespace);
}
/**
* Returns the component prefix
*
* @return string
*/
public function getComponentPrefix()
{
return $this->getComponentClass() . $this->getComponentPrefixer()->getSeparator();
}
/**
* Renders the component the viewhelper is responsible for
* TODO this can probably be improved by using renderComponent() directly
*
* @return string
*/
public function render()
{
// Create a new rendering context for the component file
$renderingContext = $this->getRenderingContext();
if ((new Typo3Version())->getMajorVersion() < 12 && $this->renderingContext->getControllerContext()) {
$renderingContext->setControllerContext($this->renderingContext->getControllerContext());
} else {
// set the original request to preserve the request attributes
// some ViewHelpers expect a ServerRequestInterface or other attributes inside the request
// e.g. f:uri.action, f:page.action
$renderingContext->setRequest($this->renderingContext->getRequest());
}
$renderingContext->setViewHelperVariableContainer($this->renderingContext->getViewHelperVariableContainer());
if (static::shouldUseTemplatePaths()) {
$renderingContext->getTemplatePaths()->setPartialRootPaths(
$this->renderingContext->getTemplatePaths()->getPartialRootPaths()
);
}
$variableContainer = $renderingContext->getVariableProvider();
// Provide information about component to renderer
$variableContainer->add('component', [
'namespace' => $this->componentNamespace,
'class' => $this->getComponentClass(),
'prefix' => $this->getComponentPrefix(),
]);
$variableContainer->add('settings', $this->componentSettings);
// Provide supplied arguments from component call to renderer
foreach ($this->argumentDefinitions as $name => $definition) {
$argumentType = $definition->getType();
if (is_a($argumentType, Slot::class, true)) {
$argument = $this->renderSlot($name);
} else {
$argument = $this->arguments[$name] ?? null;
}
$argument = $this->componentArgumentConverter->convertValueToType($argument, $argumentType);
// Provide component namespace to certain data structures
if ($argument instanceof ComponentAware) {
$argument->setComponentNamespace($this->componentNamespace);
}
// Provide rendering context to certain data structures
if ($argument instanceof RenderingContextAware) {
$argument->setRenderingContext($renderingContext);
}
$variableContainer->add($name, $argument);
}
// Initialize component rendering template
if (!isset($this->parsedTemplate)) {
$componentFile = $this->componentLoader->findComponent($this->componentNamespace);
$this->parsedTemplate = $renderingContext->getTemplateParser()->getOrParseAndStoreTemplate(
$this->getTemplateIdentifier($componentFile),
function () use ($componentFile) {
return file_get_contents($componentFile);
}
);
}
// Render component
return $this->parsedTemplate->render($renderingContext);
}
protected function renderSlot(string $name)
{
$slot = $this->arguments[$name] ?? null;
// Shortcut if template is rendered from cache
// or parameter was provided directly to the component
if (isset($slot) && !$slot instanceof RequiredSlotPlaceholder) {
return $slot;
}
// Use content specified by <fc:content /> ViewHelpers
// This is only executed for uncached templates
if (isset($this->viewHelperNode)) {
$contentViewHelpers = $this->extractContentViewHelpers($this->viewHelperNode, $this->renderingContext);
if (isset($contentViewHelpers[$name])) {
return (string) $contentViewHelpers[$name]->evaluateChildNodes($this->renderingContext);
}
}
// Use tag content for default slot
if ($name === self::DEFAULT_SLOT) {
return (string) $this->renderChildren();
}
// Required Slot parameters are checked here for existence at last
if ($slot instanceof RequiredSlotPlaceholder) {
throw new \InvalidArgumentException(sprintf(
'Slot "%s" is required by component "%s", but no value was given.',
$name,
$this->componentNamespace
), 1681728555);
}
return $slot;
}
/**
* Overwrites original compilation to store component namespace in compiled templates
*
* @param string $argumentsName
* @param string $closureName
* @param string $initializationPhpCode
* @param ViewHelperNode $node
* @param TemplateCompiler $compiler
* @return string
*/
public function compile(
$argumentsName,
$closureName,
&$initializationPhpCode,
ViewHelperNode $node,
TemplateCompiler $compiler
) {
$allowedSlots = [];
foreach ($node->getArgumentDefinitions() as $definition) {
if (is_a($definition->getType(), Slot::class, true)) {
$allowedSlots[$definition->getName()] = true;
}
}
$contentViewHelpers = $this->extractContentViewHelpers($node, $compiler->getRenderingContext());
foreach ($contentViewHelpers as $slotName => $viewHelperNode) {
if (!isset($allowedSlots[$slotName])) {
throw new \InvalidArgumentException(sprintf(
'Slot "%s" does not exist in component "%s", but was used as named slot.',
$slotName,
$this->componentNamespace
), 1681832624);
}
$childNodesAsClosure = $compiler->wrapChildNodesInClosure($viewHelperNode);
$initializationPhpCode .= sprintf('%s[\'%s\'] = %s;', $argumentsName, $slotName, $childNodesAsClosure) . chr(10);
}
return sprintf(
'%s::renderComponent(%s, %s, $renderingContext, %s)',
get_class($this),
$argumentsName,
$closureName,
var_export($this->componentNamespace, true)
);
}
/**
* Replacement for renderStatic() to provide component namespace to ViewHelper
*
* @param array $arguments
* @param \Closure $renderChildrenClosure
* @param RenderingContextInterface $renderingContext
* @param string $componentNamespace
* @return mixed
*/
public static function renderComponent(
array $arguments,
\Closure $renderChildrenClosure,
RenderingContextInterface $renderingContext,
$componentNamespace
) {
$container = GeneralUtility::makeInstance(ContainerInterface::class);
$componentRenderer = $container->get(static::class);
$componentRenderer->setComponentNamespace($componentNamespace);
return $renderingContext->getViewHelperInvoker()->invoke(
$componentRenderer,
$arguments,
$renderingContext,
$renderChildrenClosure
);
}
/**
* Initializes the component arguments based on the component definition
*
* @return void
* @throws Exception
*/
public function initializeArguments()
{
$this->registerArgument(
'class',
'string',
'Additional CSS classes for the component'
);
$this->registerArgument(
self::DEFAULT_SLOT,
Slot::class,
'Main content of the component; falls back to ViewHelper tag content',
false,
null,
true
);
$this->initializeComponentParams();
}
/**
* Initialize all arguments and return them
*
* @return ArgumentDefinition[]
*/
public function prepareArguments()
{
// Store caches for components separately because they can't be grouped by class name
if (isset(self::$componentArgumentDefinitionCache[$this->componentNamespace])) {
$this->argumentDefinitions = self::$componentArgumentDefinitionCache[$this->componentNamespace];
} else {
$this->initializeArguments();
self::$componentArgumentDefinitionCache[$this->componentNamespace] = $this->argumentDefinitions;
}
return $this->argumentDefinitions;
}
/**
* Default implementation of validating additional, undeclared arguments.
* In this implementation the behavior is to consistently throw an error
* about NOT supporting any additional arguments. This method MUST be
* overridden by any ViewHelper that desires this support and this inherited
* method must not be called, obviously.
*
* @throws Exception
* @param array $arguments
* @return void
*/
public function validateAdditionalArguments(array $arguments)
{
if (!empty($arguments)) {
throw new Exception(
sprintf(
'Undeclared arguments passed to component %s: %s. Valid arguments are: %s',
$this->componentNamespace,
implode(', ', array_keys($arguments)),
implode(', ', array_keys($this->argumentDefinitions))
),
1530632359
);
}
}
/**
* Validate arguments, and throw exception if arguments do not validate.
*
* @return void
* @throws \InvalidArgumentException
*/
public function validateArguments()
{
$argumentDefinitions = $this->prepareArguments();
foreach ($argumentDefinitions as $argumentName => $registeredArgument) {
if ($this->hasArgument($argumentName)) {
$value = $this->arguments[$argumentName];
$defaultValue = $registeredArgument->getDefaultValue();
$type = $registeredArgument->getType();
if ($value !== $defaultValue && $type !== 'mixed') {
$givenType = is_object($value) ? get_class($value) : gettype($value);
if (!$this->isValidType($type, $value)
&& !$this->componentArgumentConverter->canTypeBeConvertedToType($givenType, $type)
) {
throw new \InvalidArgumentException(
'The argument "' . $argumentName . '" was registered with type "' . $type . '", but is of type "' .
$givenType . '" in component "' . $this->componentNamespace . '".',
1530632537
);
}
}
}
}
}
/**
* Creates ViewHelper arguments based on the params defined in the component definition
*
* @return void
*/
protected function initializeComponentParams()
{
$renderingContext = $this->getRenderingContext();
$componentFile = $this->componentLoader->findComponent($this->componentNamespace);
// Parse component template without using the cache
$parsedTemplate = $renderingContext->getTemplateParser()->parse(
file_get_contents($componentFile),
$this->getTemplateIdentifier($componentFile)
);
// Extract all component viewhelpers
$componentNodes = $this->extractViewHelpers(
$parsedTemplate->getRootNode(),
ComponentViewHelper::class
);
if (count($componentNodes) > 1) {
throw new Exception(sprintf(
'Only one component per file allowed in: %s',
$componentFile
), 1527779393);
}
if (!empty($componentNodes)) {
// Extract all parameter definitions
$paramNodes = $this->extractViewHelpers(
$componentNodes[0],
ParamViewHelper::class
);
// Register argument definitions from parameter viewhelpers
foreach ($paramNodes as $paramNode) {
$param = [];
foreach ($paramNode->getArguments() as $argumentName => $argumentNode) {
$param[$argumentName] = $argumentNode->evaluate($renderingContext);
}
// Use tag content as default value instead of attribute
if (!isset($param['default'])) {
$param['default'] = implode('', array_map(function ($node) use ($renderingContext) {
return $node->evaluate($renderingContext);
}, $paramNode->getChildNodes()));
$param['default'] = $param['default'] === '' ? null : $param['default'];
}
if (in_array($param['name'], $this->reservedArguments)) {
throw new Exception(sprintf(
'The argument "%s" defined in "%s" cannot be used because it is reserved.',
$param['name'],
$this->getComponentNamespace()
), 1532960145);
}
// Resolve type aliases
$param['type'] = $this->componentArgumentConverter->resolveTypeAlias($param['type']);
// Enforce boolean node, see implementation in ViewHelperNode::rewriteBooleanNodesInArgumentsObjectTree()
if ($param['type'] === 'boolean' || $param['type'] === 'bool') {
$param['default'] = BooleanNode::convertToBoolean($param['default'], $renderingContext);
// Make sure that default value for object parameters is either a valid object or null
} elseif (class_exists($param['type']) &&
!$param['default'] instanceof $param['type'] &&
!$this->componentArgumentConverter->canTypeBeConvertedToType(gettype($param['default']), $param['type'])
) {
$param['default'] = null;
}
$optional = $param['optional'] ?? false;
$description = $param['description'] ?? '';
$escape = is_subclass_of($param['type'], EscapedParameter::class) ? true : null;
// Special handling for required Slot parameters
// This is necessary to be able to use <fc:content /> instead of a component parameter because
// the Fluid parser checks for existing arguments early in the parsing process
if (is_a($param['type'], Slot::class, true) && !$optional) {
$optional = true;
$param['default'] = new RequiredSlotPlaceholder;
}
$this->registerArgument($param['name'], $param['type'], $description, !$optional, $param['default'], $escape);
}
}
}
/**
* Extracts all <fc:content /> ViewHelpers from Fluid template node
*
* @param NodeInterface $node
* @param RenderingContext $renderingContext
* @return array
*/
protected function extractContentViewHelpers(NodeInterface $node, RenderingContext $renderingContext): array
{
return array_reduce(
$this->extractViewHelpers($node, ContentViewHelper::class, false),
function (array $nodes, ViewHelperNode $node) use ($renderingContext) {
$slotArgument = $node->getArguments()['slot'] ?? null;
$slotName = ($slotArgument) ? $slotArgument->evaluate($renderingContext) : self::DEFAULT_SLOT;
$nodes[$slotName] = $node;
return $nodes;
},
[]
);
}
/**
* Extract all ViewHelpers of a certain type from a Fluid template node
*
* @param NodeInterface $node
* @param string $viewHelperClassName
* @return array
*/
protected function extractViewHelpers(NodeInterface $node, string $viewHelperClassName, bool $recursive = true): array
{
$viewHelperNodes = [];
if ($node instanceof EscapingNode) {
$node = $node->getNode();
}
if ($node instanceof ViewHelperNode && $node->getViewHelperClassName() === $viewHelperClassName) {
$viewHelperNodes[] = $node;
} else {
foreach ($node->getChildNodes() as $childNode) {
if ($recursive === false && $childNode instanceof ViewHelperNode && ($childNode->getViewHelperClassName() === ComponentViewHelper::class || $childNode->getUninitializedViewHelper() instanceof ComponentRenderer)) {
continue;
}
$viewHelperNodes = array_merge(
$viewHelperNodes,
$this->extractViewHelpers($childNode, $viewHelperClassName, $recursive)
);
}
}
return $viewHelperNodes;
}
/**
* Returns an identifier by which fluid templates will be stored in the cache
*
* @return string
*/
protected function getTemplateIdentifier(string $pathAndFilename, string $prefix = 'fluidcomponent')
{
$templateModifiedTimestamp = $pathAndFilename !== 'php://stdin' && file_exists($pathAndFilename) ? filemtime($pathAndFilename) : 0;
return sprintf(
'%s_%s_%s',
$prefix,
substr(strrchr($this->componentNamespace, "\\"), 1),
sha1($pathAndFilename . '|' . $templateModifiedTimestamp)
);
}
/**
* Returns the prefixer object responsible for the current component namespaces
*
* @return ComponentPrefixerInterface
*/
protected function getComponentPrefixer()
{
if (!isset(self::$componentPrefixerCache[$this->componentNamespace])) {
if (isset($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['fluid_components']['prefixer']) &&
is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['fluid_components']['prefixer'])
) {
arsort($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['fluid_components']['prefixer']);
foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['fluid_components']['prefixer'] as $namespace => $prefixer) {
$namespace = ltrim($namespace, '\\');
if (strpos($this->componentNamespace, $namespace) === 0) {
$componentPrefixerClass = $prefixer;
break;
}
}
}
if (empty($componentPrefixerClass)) {
$componentPrefixerClass = GenericComponentPrefixer::class;
}
if ($this->container->has($componentPrefixerClass)) {
$componentPrefixer = $this->container->get($componentPrefixerClass);
} else {
$componentPrefixer = GeneralUtility::makeInstance($componentPrefixerClass);
}
if (!($componentPrefixer instanceof ComponentPrefixerInterface)) {
throw new Exception(sprintf(
'Invalid component prefixer: %s',
$componentPrefixerClass
), 1530608357);
}
self::$componentPrefixerCache[$this->componentNamespace] = $componentPrefixer;
}
return self::$componentPrefixerCache[$this->componentNamespace];
}
/**
* @return RenderingContext
*/
protected function getRenderingContext(): RenderingContext
{
if ($this->container->has(RenderingContextFactory::class)) {
return $this->container->get(RenderingContextFactory::class)->create();
} else {
return GeneralUtility::makeInstance(RenderingContext::class);
}
}
/**
* @return bool
*/
protected static function shouldUseTemplatePaths(): bool
{
static $assertion = null;
if ($assertion === null) {
$assertion = GeneralUtility::makeInstance(Features::class)->isFeatureEnabled('fluidComponents.partialsInComponents');
}
return $assertion;
}
}