-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathTemplate.php
More file actions
655 lines (584 loc) · 19.5 KB
/
Copy pathTemplate.php
File metadata and controls
655 lines (584 loc) · 19.5 KB
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
<?php
/**
* This file is part of MetaModels/core.
*
* (c) 2012-2025 The MetaModels team.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* This project is provided in good faith and hope to be usable by anyone.
*
* @package MetaModels/core
* @author Christian Schiffler <c.schiffler@cyberspectrum.de>
* @author David Maack <david.maack@arcor.de>
* @author Richard Henkenjohann <richardhenkenjohann@googlemail.com>
* @author Stefan Heimes <stefan_heimes@hotmail.com>
* @author Sven Baumann <baumann.sv@gmail.com>
* @author David Molineus <david.molineus@netzmacht.de>
* @author Ingolf Steinhardt <info@e-spin.de>
* @copyright 2012-2025 The MetaModels team.
* @license https://github.com/MetaModels/core/blob/master/LICENSE LGPL-3.0-or-later
* @filesource
*/
namespace MetaModels\Render;
use Contao\BackendTemplate;
use Contao\CoreBundle\Framework\Adapter;
use Contao\FrontendTemplate;
use Contao\System;
use Contao\TemplateLoader;
use ContaoCommunityAlliance\DcGeneral\Contao\RequestScopeDeterminator;
use Exception;
use MetaModels\Helper\ContaoController;
use RuntimeException;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Template class for MetaModels.
* In most aspects this behaves identically to the FrontendTemplate class from Contao, but it differs in respect to
* format selection.
* The format is being determined upon parsing and not upon instantiation. There is also an optional "fail on not
* found" flag, which defaults to false and therefore one can parse the template and have zero output instead of
* cluttering the frontend with exceptions.
*
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
* @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
*/
class Template
{
/**
* Template file.
*
* @var string
*/
protected $strTemplate;
/**
* Parent template.
*
* @var string|null
*/
protected $strParent;
/**
* Default template.
*
* @var string|null
*/
protected $strDefault;
/**
* Template data.
*
* @var array
*/
protected $arrData = [];
/**
* Current output format. Only valid when within {@link MetaModelTemplate::parse()}.
*
* @var string
*/
protected $strFormat = '';
/**
* Blocks.
*
* @var array
*/
protected $arrBlocks = [];
/**
* Block names.
*
* @var array
*/
protected $arrBlockNames = [];
/**
* The template loader.
*
* @var Adapter|Adapter<TemplateLoader> Template loader adapter.
*/
protected $templateLoader;
/**
* Request scope determinator.
*
* @var RequestScopeDeterminator
*/
protected $scopeDeterminator;
/**
* Template path cache.
*
* Storing state of template path detection in a cache array for each template format and custom location.
*
* @var array<string, array<string, array<string, string|false>>>
*/
protected static $templatePathCache = [];
/**
* Makes all protected methods from class Controller callable publicly.
*
* @param string $strMethod The method name.
* @param array $arrArgs The parameters for the method.
*
* @return mixed
*/
public function __call($strMethod, $arrArgs)
{
if (isset($this->$strMethod) && \is_callable($this->$strMethod)) {
return \call_user_func_array($this->$strMethod, $arrArgs);
}
/** @psalm-suppress DeprecatedClass */
return \call_user_func_array(array(ContaoController::getInstance(), $strMethod), $arrArgs);
}
/**
* Create a new template instance.
*
* @param string $strTemplate The name of the template file.
* @param Adapter|Adapter<TemplateLoader>|null $templateLoader Template loader adapter.
* @param RequestScopeDeterminator|null $scopeDeterminator Request scope determinator.
*/
public function __construct(
$strTemplate = '',
?Adapter $templateLoader = null,
?RequestScopeDeterminator $scopeDeterminator = null
) {
$this->strTemplate = $strTemplate;
if (null === $templateLoader) {
// @codingStandardsIgnoreStart
@trigger_error(
'Not passing the template loader as 2nd argument to "' . __METHOD__ . '" is deprecated ' .
'and will cause an error in MetaModels 3.0',
E_USER_DEPRECATED
);
// @codingStandardsIgnoreEnd
$templateLoader = System::getContainer()->get('contao.framework')->getAdapter(TemplateLoader::class);
assert($templateLoader instanceof Adapter);
}
$this->templateLoader = $templateLoader;
if (null === $scopeDeterminator) {
// @codingStandardsIgnoreStart
@trigger_error(
'Not passing the request scope determinator as 3rd argument to "' . __METHOD__ . '" is deprecated ' .
'and will cause an error in MetaModels 3.0',
E_USER_DEPRECATED
);
// @codingStandardsIgnoreEnd
$scopeDeterminator = System::getContainer()->get('cca.dc-general.scope-matcher');
assert($scopeDeterminator instanceof RequestScopeDeterminator);
}
$this->scopeDeterminator = $scopeDeterminator;
}
/**
* Set an object property.
*
* @param string $strKey The name of the property.
* @param mixed $varValue The value to set.
*
* @return void
*/
public function __set($strKey, $varValue)
{
$this->arrData[$strKey] = $varValue;
}
/**
* Return an object property.
*
* @param string $strKey The name of the property.
*
* @return mixed
*
* @SuppressWarnings(PHPMD.Superglobals)
* @SuppressWarnings(PHPMD.CamelCaseVariableName)
*/
public function __get($strKey)
{
if (\array_key_exists($strKey, $this->arrData)) {
return $this->arrData[$strKey];
}
if (!empty($GLOBALS['TL_CONFIG']['debugMode'])) {
\trigger_error($this->getName() . ': Undefined template variable: ' . $strKey, E_USER_WARNING);
}
return null;
}
/**
* Check whether a property is set.
*
* @param string $strKey The name of the property.
*
* @return boolean
*/
public function __isset($strKey)
{
return isset($this->arrData[$strKey]);
}
/**
* Set the template data from an array.
*
* @param array $arrData The properties to be set.
*
* @return void
*/
public function setData($arrData)
{
$this->arrData = $arrData;
}
/**
* Return the template data as array.
*
* @return array
*/
public function getData()
{
return $this->arrData;
}
/**
* Set the template name.
*
* @param string $strTemplate The new name.
*
* @return void
*/
public function setName($strTemplate)
{
$this->strTemplate = $strTemplate;
}
/**
* Return the template name.
*
* @return string
*/
public function getName()
{
return $this->strTemplate;
}
/**
* Print all template variables to the screen using print_r.
*
* @return void
*
* @SuppressWarnings(PHPMD.DevelopmentCodeFragment)
*/
public function showTemplateVars()
{
echo "<pre>\n";
// @codingStandardsIgnoreStart - We really want to keep this debug function here.
\print_r($this->arrData);
// @codingStandardsIgnoreEnd
echo "</pre>\n";
}
/**
* Print all template variables to the screen using var_dump.
*
* @return void
*
* @SuppressWarnings(PHPMD.DevelopmentCodeFragment)
*
* @psalm-suppress ForbiddenCode
*/
public function dumpTemplateVars()
{
echo "<pre>\n";
// @codingStandardsIgnoreStart - We really want to keep this debug function here.
\var_dump($this->arrData);
// @codingStandardsIgnoreEnd
echo "</pre>\n";
}
/**
* Find a particular template file and return its path.
*
* @param string $strTemplate Name of the template file.
* @param string $strFormat The format to search for.
* @param bool $blnFailIfNotFound Boolean flag telling if an Exception shall be thrown when the file can not
* be found.
*
* @throws RuntimeException When the flag has been set and the file has not been found.
*
* @return string|null
*
* @SuppressWarnings(PHPMD.Superglobals)
* @SuppressWarnings(PHPMD.CamelCaseVariableName)
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
protected function getTemplate($strTemplate, $strFormat = 'html5', $blnFailIfNotFound = false)
{
$strTemplate = \basename($strTemplate);
$strCustom = 'templates';
// Check for a theme folder if scope frontend and a normal page.
if (isset($GLOBALS['objPage']) && $this->scopeDeterminator->currentScopeIsFrontend()) {
$tmpDir = \str_replace('../', '', (string) $GLOBALS['objPage']->templateGroup);
if ('' !== $tmpDir) {
$strCustom = $tmpDir;
}
}
if (
isset(self::$templatePathCache[$strTemplate][$strFormat])
&& \array_key_exists($strCustom, self::$templatePathCache[$strTemplate][$strFormat])
) {
$value = self::$templatePathCache[$strTemplate][$strFormat][$strCustom] !== false
? self::$templatePathCache[$strTemplate][$strFormat][$strCustom]
: null;
if ($blnFailIfNotFound && null === $value) {
throw new \Exception('Could not find template "' . $strTemplate . '"');
}
return $value;
}
try {
/** @psalm-suppress UndefinedMagicMethod */
self::$templatePathCache[$strTemplate][$strFormat][$strCustom] = $this->templateLoader->getPath(
$strTemplate,
$strFormat,
$strCustom
);
return self::$templatePathCache[$strTemplate][$strFormat][$strCustom];
} catch (Exception $exception) {
self::$templatePathCache[$strTemplate][$strFormat][$strCustom] = false;
if ($blnFailIfNotFound) {
throw new RuntimeException(
\sprintf('Could not find template %s.%s', $strTemplate, $strFormat),
1,
$exception
);
}
}
return null;
}
/**
* Call the parse Template HOOK.
*
* @return void
*
* @SuppressWarnings(PHPMD.Superglobals)
* @SuppressWarnings(PHPMD.CamelCaseVariableName)
*/
protected function callParseTemplateHook()
{
if (
isset($GLOBALS['METAMODEL_HOOKS']['parseTemplate'])
&& \is_array($GLOBALS['METAMODEL_HOOKS']['parseTemplate'])
) {
foreach ($GLOBALS['METAMODEL_HOOKS']['parseTemplate'] as $callback) {
[$strClass, $strMethod] = $callback;
$objCallback = (\in_array('getInstance', \get_class_methods($strClass)))
? \call_user_func(array($strClass, 'getInstance'))
: new $strClass();
$objCallback->$strMethod($this);
}
}
}
/**
* Parse the template file and return it as string.
*
* @param string $strOutputFormat The desired output format.
* @param boolean $blnFailIfNotFound If set to true, the template object will throw an exception if the template
* can not be found. Defaults to false.
*
* @return string The parsed template.
*/
public function parse($strOutputFormat, $blnFailIfNotFound = false)
{
if ($this->strTemplate === '') {
return '';
}
// Set the format.
$this->strFormat = $strOutputFormat;
// HOOK: add custom parse filters.
$this->callParseTemplateHook();
$strBuffer = '';
// Start with the template itself.
$this->strParent = $this->strTemplate;
// Include the parent templates.
while ($this->strParent !== null) {
$strCurrent = $this->strParent;
$strParent = $this->strDefault
?? $this->getTemplate($this->strParent, $this->strFormat, $blnFailIfNotFound);
// Check if we have the template.
if (null === $strParent) {
return \sprintf(
'Template %s.%s not found (it is maybe within a unreachable theme folder?).',
$this->strParent,
$this->strFormat
);
}
// Reset the flags.
$this->strParent = null;
$this->strDefault = null;
\ob_start();
assert(\is_file($strParent));
/** @var string|null $this->strParent */
include($strParent);
// Capture the output of the root template.
if ($this->strParent === null) {
$strBuffer = \ob_get_contents();
} elseif ($this->strParent === $strCurrent) {
$this->strDefault = $this->getTemplate($this->strParent, $this->strFormat, $blnFailIfNotFound);
}
\ob_end_clean();
}
// Reset the internal arrays.
$this->arrBlocks = [];
// Add start and end markers in debug mode.
$container = System::getContainer();
if (
($container instanceof ContainerInterface)
&& true === $container->getParameter('kernel.debug')
&& ('html5' === $this->strFormat)
) {
$rootDir = $container->getParameter('kernel.project_dir');
assert(\is_string($rootDir));
$strRelPath =
\str_replace($rootDir . '/', '', (string) $this->getTemplate($this->strTemplate, $this->strFormat));
$strBuffer = <<<EOF
<!-- TEMPLATE START: $strRelPath -->
$strBuffer
<!-- TEMPLATE END: $strRelPath -->
EOF;
}
return (string) $strBuffer;
}
/**
* Protected as only the included template file shall be able to call.
*
* This is needed to remain protected, as outside from {@link Template::parse()} the format is undefined.
*
* @return string
*/
protected function getFormat()
{
return $this->strFormat;
}
/**
* Static convenience method to perform the whole rendering within one line of code.
*
* @param string $strTemplate Name of the template file.
* @param string $strOutputFormat The desired output format.
* @param array $arrTplData The data to use in the template.
*
* @param bool $blnFailIfNotFound If set to true, the template object will throw an exception if the template
* can not be found. Defaults to false.
*
* @return string
*/
public static function render($strTemplate, $strOutputFormat, $arrTplData, $blnFailIfNotFound = false)
{
$objTemplate = new self($strTemplate);
$objTemplate->setData($arrTplData);
return $objTemplate->parse($strOutputFormat, $blnFailIfNotFound);
}
/**
* Extend another template
*
* @param string $strName The template name.
*
* @return void
*/
public function extend($strName)
{
$this->strParent = $strName;
}
/**
* Insert the content of the parent block
*
* @return void
*/
public function parent()
{
echo '[[TL_PARENT]]';
}
/**
* Start a new block
*
* @param string $strName The block name.
*
* @return void
*
* @throws Exception If a child templates contains nested blocks.
*/
public function block($strName)
{
$this->arrBlockNames[] = $strName;
// Root template.
if ($this->strParent === null) {
// Register the block name.
if (!isset($this->arrBlocks[$strName])) {
$this->arrBlocks[$strName] = '[[TL_PARENT]]';
} elseif (\is_array($this->arrBlocks[$strName])) {
// Combine the contents of the child blocks
$callback = static function (string $current, string $parent): string {
return \str_replace('[[TL_PARENT]]', $parent, $current);
};
$this->arrBlocks[$strName] = \array_reduce($this->arrBlocks[$strName], $callback, '[[TL_PARENT]]');
}
// Handle nested blocks.
if ($this->arrBlocks[$strName] !== '[[TL_PARENT]]') {
// Output everything before the first TL_PARENT tag.
if (\strpos($this->arrBlocks[$strName], '[[TL_PARENT]]') !== false) {
[$content] = \explode('[[TL_PARENT]]', $this->arrBlocks[$strName], 2);
echo $content;
} else {
// Output the current block and start a new output buffer to remove the following blocks
echo $this->arrBlocks[$strName];
\ob_start();
}
}
} else {
// Child template
// Clean the output buffer.
\ob_end_clean();
// Check for nested blocks.
if (\count($this->arrBlockNames) > 1) {
throw new Exception('Nested blocks are not allowed in child templates');
}
// Start a new output buffer.
\ob_start();
}
}
/**
* End a block
*
* @return void
*
* @throws Exception If there is no open block.
*/
public function endblock()
{
// Check for open blocks.
if (empty($this->arrBlockNames)) {
throw new Exception('You must start a block before you can end it');
}
// Get the block name
$name = \array_pop($this->arrBlockNames);
// Root template.
if ($this->strParent === null) {
// Handle nested blocks
if ($this->arrBlocks[$name] !== '[[TL_PARENT]]') {
// Output everything after the first TL_PARENT tag
if (\str_contains($this->arrBlocks[$name], '[[TL_PARENT]]')) {
[, $content] = \array_merge(\explode('[[TL_PARENT]]', $this->arrBlocks[$name], 2), ['']);
echo $content;
} else {
// Remove the overwritten content
\ob_end_clean();
}
}
} else {
// Child template
// Capture the block content.
$this->arrBlocks[$name][] = \ob_get_clean();
// Start a new output buffer
\ob_start();
}
}
/**
* Insert a template
*
* @param string $strName The template name.
* @param array|null $arrData An optional data array.
*
* @return void
*/
public function insert($strName, ?array $arrData = null)
{
if ($this->scopeDeterminator->currentScopeIsBackend()) {
$objTemplate = new BackendTemplate($strName);
} else {
$objTemplate = new FrontendTemplate($strName);
}
if ($arrData !== null) {
$objTemplate->setData($arrData);
}
echo $objTemplate->parse();
}
}