• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nette / latte / 18955707548

30 Oct 2025 09:34PM UTC coverage: 93.854% (-0.08%) from 93.929%
18955707548

push

github

dg
Released version 3.0.24

5238 of 5581 relevant lines covered (93.85%)

0.94 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

84.92
/src/Latte/Engine.php
1
<?php
2

3
/**
4
 * This file is part of the Latte (https://latte.nette.org)
5
 * Copyright (c) 2008 David Grudl (https://davidgrudl.com)
6
 */
7

8
declare(strict_types=1);
9

10
namespace Latte;
11

12
use Latte\Compiler\Nodes\TemplateNode;
13
use function array_map, array_merge, class_exists, extension_loaded, filemtime, get_debug_type, get_object_vars, is_array, md5, preg_match, serialize, strpos, substr;
14
use const PHP_VERSION_ID;
15

16

17
/**
18
 * Templating engine Latte.
19
 */
20
class Engine
21
{
22
        public const Version = '3.0.24';
23
        public const VersionId = 30024;
24

25
        /** @deprecated use Engine::Version */
26
        public const
27
                VERSION = self::Version,
28
                VERSION_ID = self::VersionId;
29

30
        /** @deprecated use ContentType::* */
31
        public const
32
                CONTENT_HTML = ContentType::Html,
33
                CONTENT_XML = ContentType::Xml,
34
                CONTENT_JS = ContentType::JavaScript,
35
                CONTENT_CSS = ContentType::Css,
36
                CONTENT_ICAL = ContentType::ICal,
37
                CONTENT_TEXT = ContentType::Text;
38

39
        private ?Loader $loader = null;
40
        private Runtime\FilterExecutor $filters;
41
        private Runtime\FunctionExecutor $functions;
42
        private \stdClass $providers;
43

44
        /** @var Extension[] */
45
        private array $extensions = [];
46
        private string $contentType = ContentType::Html;
47
        private Cache $cache;
48
        private bool $strictTypes = false;
49
        private bool $strictParsing = false;
50
        private ?Policy $policy = null;
51
        private bool $sandboxed = false;
52
        private ?string $phpBinary = null;
53
        private ?string $configurationHash;
54
        private ?string $locale = null;
55
        private ?string $syntax = null;
56

57

58
        public function __construct()
59
        {
60
                $this->cache = new Cache;
1✔
61
                $this->filters = new Runtime\FilterExecutor;
1✔
62
                $this->functions = new Runtime\FunctionExecutor;
1✔
63
                $this->providers = new \stdClass;
1✔
64
                $this->addExtension(new Essential\CoreExtension);
1✔
65
                $this->addExtension(new Sandbox\SandboxExtension);
1✔
66
        }
1✔
67

68

69
        /**
70
         * Renders template to output.
71
         * @param  object|mixed[]  $params
72
         */
73
        public function render(string $name, object|array $params = [], ?string $block = null): void
1✔
74
        {
75
                $template = $this->createTemplate($name, $this->processParams($params));
1✔
76
                $template->global->coreCaptured = false;
1✔
77
                $template->render($block);
1✔
78
        }
1✔
79

80

81
        /**
82
         * Renders template to string.
83
         * @param  object|mixed[]  $params
84
         */
85
        public function renderToString(string $name, object|array $params = [], ?string $block = null): string
1✔
86
        {
87
                $template = $this->createTemplate($name, $this->processParams($params));
1✔
88
                $template->global->coreCaptured = true;
1✔
89
                return $template->capture(fn() => $template->render($block));
1✔
90
        }
91

92

93
        /**
94
         * Creates template object.
95
         * @param  mixed[]  $params
96
         */
97
        public function createTemplate(string $name, array $params = [], bool $clearCache = true): Runtime\Template
1✔
98
        {
99
                $this->configurationHash = $clearCache ? null : $this->configurationHash;
1✔
100
                $class = $this->loadTemplate($name);
1✔
101
                $this->providers->fn = $this->functions;
1✔
102
                return new $class(
1✔
103
                        $this,
1✔
104
                        $params,
105
                        $this->filters,
1✔
106
                        $this->providers,
1✔
107
                        $name,
108
                );
109
        }
110

111

112
        /**
113
         * Compiles template to PHP code.
114
         */
115
        public function compile(string $name): string
1✔
116
        {
117
                if ($this->sandboxed && !$this->policy) {
1✔
118
                        throw new \LogicException('In sandboxed mode you need to set a security policy.');
1✔
119
                }
120

121
                $template = $this->getLoader()->getContent($name);
1✔
122

123
                try {
124
                        $node = $this->parse($template);
1✔
125
                        $this->applyPasses($node);
1✔
126
                        $compiled = $this->generate($node, $name);
1✔
127

128
                } catch (\Throwable $e) {
1✔
129
                        if (!$e instanceof CompileException && !$e instanceof SecurityViolationException) {
1✔
130
                                $e = new CompileException("Thrown exception '{$e->getMessage()}'", previous: $e);
1✔
131
                        }
132

133
                        throw $e->setSource($template, $name);
1✔
134
                }
135

136
                if ($this->phpBinary) {
1✔
137
                        Compiler\PhpHelpers::checkCode($this->phpBinary, $compiled, "(compiled $name)");
×
138
                }
139

140
                return $compiled;
1✔
141
        }
142

143

144
        /**
145
         * Parses template to AST node.
146
         */
147
        public function parse(string $template): TemplateNode
1✔
148
        {
149
                $parser = new Compiler\TemplateParser;
1✔
150
                $parser->getLexer()->setSyntax($this->syntax);
1✔
151
                $parser->strict = $this->strictParsing;
1✔
152

153
                foreach ($this->extensions as $extension) {
1✔
154
                        $extension->beforeCompile($this);
1✔
155
                        $parser->addTags($extension->getTags());
1✔
156
                }
157

158
                return $parser
159
                        ->setContentType($this->contentType)
1✔
160
                        ->setPolicy($this->getPolicy(effective: true))
1✔
161
                        ->parse($template);
1✔
162
        }
163

164

165
        /**
166
         * Calls node visitors.
167
         */
168
        public function applyPasses(TemplateNode &$node): void
1✔
169
        {
170
                $passes = [];
1✔
171
                foreach ($this->extensions as $extension) {
1✔
172
                        $passes = array_merge($passes, $extension->getPasses());
1✔
173
                }
174

175
                $passes = Helpers::sortBeforeAfter($passes);
1✔
176
                foreach ($passes as $pass) {
1✔
177
                        $pass = $pass instanceof \stdClass ? $pass->subject : $pass;
1✔
178
                        ($pass)($node);
1✔
179
                }
180
        }
1✔
181

182

183
        /**
184
         * Generates compiled PHP code.
185
         */
186
        public function generate(TemplateNode $node, string $name): string
1✔
187
        {
188
                $generator = new Compiler\TemplateGenerator;
1✔
189
                return $generator->generate(
1✔
190
                        $node,
1✔
191
                        $this->getTemplateClass($name),
1✔
192
                        $name,
193
                        $this->strictTypes,
1✔
194
                );
195
        }
196

197

198
        /**
199
         * Compiles template to cache.
200
         * @throws \LogicException
201
         */
202
        public function warmupCache(string $name): void
1✔
203
        {
204
                if (!$this->cache->directory) {
1✔
205
                        throw new \LogicException('Path to temporary directory is not set.');
×
206
                }
207

208
                $this->loadTemplate($name);
1✔
209
        }
1✔
210

211

212
        private function loadTemplate(string $name): string
1✔
213
        {
214
                $class = $this->getTemplateClass($name);
1✔
215
                if (class_exists($class, false)) {
1✔
216
                        // nothing
217
                } elseif ($this->cache->directory) {
1✔
218
                        $this->cache->loadOrCreate($this, $name);
1✔
219
                } else {
220
                        $compiled = $this->compile($name);
1✔
221
                        if (@eval(substr($compiled, 5)) === false) { // @ is escalated to exception, substr removes <?php
1✔
222
                                throw (new CompileException('Error in template: ' . error_get_last()['message']))
×
223
                                        ->setSource($compiled, "$name (compiled)");
×
224
                        }
225
                }
226
                return $class;
1✔
227
        }
228

229

230
        /**
231
         * Returns the file path where compiled template will be cached.
232
         */
233
        public function getCacheFile(string $name): string
1✔
234
        {
235
                return $this->cache->generateFilePath($this, $name);
1✔
236
        }
237

238

239
        /**
240
         * Returns the PHP class name for compiled template.
241
         */
242
        public function getTemplateClass(string $name): string
1✔
243
        {
244
                return 'Template_' . $this->generateTemplateHash($name);
1✔
245
        }
246

247

248
        /**
249
         * Generates unique hash for template based on current configuration.
250
         * Used to create isolated cache files for different engine configurations.
251
         * @internal
252
         */
253
        public function generateTemplateHash(string $name): string
1✔
254
        {
255
                $hash = $this->configurationHash ?? md5(serialize($this->getCacheKey()));
1✔
256
                $hash .= $this->getLoader()->getUniqueId($name);
1✔
257
                return substr(md5($hash), 0, 10);
1✔
258
        }
259

260

261
        /**
262
         * Returns values that determine isolation for different configurations.
263
         * When any of these values change, a new compiled template is created to avoid conflicts.
264
         */
265
        protected function getCacheKey(): array
266
        {
267
                return [
268
                        $this->contentType,
1✔
269
                        $this->strictTypes,
1✔
270
                        $this->strictParsing,
1✔
271
                        $this->syntax,
1✔
272
                        array_map(
1✔
273
                                fn($extension) => [get_debug_type($extension), $extension->getCacheKey($this)],
1✔
274
                                $this->extensions,
1✔
275
                        ),
276
                ];
277
        }
278

279

280
        /**
281
         * Registers run-time filter.
282
         */
283
        public function addFilter(string $name, callable $callback): static
1✔
284
        {
285
                if (!preg_match('#^[a-z]\w*$#iD', $name)) {
1✔
286
                        throw new \LogicException("Invalid filter name '$name'.");
×
287
                }
288

289
                $this->filters->add($name, $callback);
1✔
290
                return $this;
1✔
291
        }
292

293

294
        /**
295
         * Registers filter loader.
296
         */
297
        public function addFilterLoader(callable $loader): static
1✔
298
        {
299
                $this->filters->add(null, $loader);
1✔
300
                return $this;
1✔
301
        }
302

303

304
        /**
305
         * Returns all run-time filters.
306
         * @return callable[]
307
         */
308
        public function getFilters(): array
309
        {
310
                return $this->filters->getAll();
1✔
311
        }
312

313

314
        /**
315
         * Call a run-time filter.
316
         * @param  mixed[]  $args
317
         */
318
        public function invokeFilter(string $name, array $args): mixed
1✔
319
        {
320
                return ($this->filters->$name)(...$args);
1✔
321
        }
322

323

324
        /**
325
         * Adds new extension.
326
         */
327
        public function addExtension(Extension $extension): static
1✔
328
        {
329
                $this->extensions[] = $extension;
1✔
330
                foreach ($extension->getFilters() as $name => $value) {
1✔
331
                        $this->filters->add($name, $value);
1✔
332
                }
333

334
                foreach ($extension->getFunctions() as $name => $value) {
1✔
335
                        $this->functions->add($name, $value);
1✔
336
                }
337

338
                foreach ($extension->getProviders() as $name => $value) {
1✔
339
                        $this->providers->$name = $value;
×
340
                }
341
                return $this;
1✔
342
        }
343

344

345
        /** @return Extension[] */
346
        public function getExtensions(): array
347
        {
348
                return $this->extensions;
1✔
349
        }
350

351

352
        /**
353
         * Registers run-time function.
354
         */
355
        public function addFunction(string $name, callable $callback): static
1✔
356
        {
357
                if (!preg_match('#^[a-z]\w*$#iD', $name)) {
1✔
358
                        throw new \LogicException("Invalid function name '$name'.");
×
359
                }
360

361
                $this->functions->add($name, $callback);
1✔
362
                return $this;
1✔
363
        }
364

365

366
        /**
367
         * Call a run-time function.
368
         * @param  mixed[]  $args
369
         */
370
        public function invokeFunction(string $name, array $args): mixed
1✔
371
        {
372
                return ($this->functions->$name)(null, ...$args);
1✔
373
        }
374

375

376
        /**
377
         * @return callable[]
378
         */
379
        public function getFunctions(): array
380
        {
381
                return $this->functions->getAll();
1✔
382
        }
383

384

385
        /**
386
         * Adds new provider.
387
         */
388
        public function addProvider(string $name, mixed $provider): static
1✔
389
        {
390
                if (!preg_match('#^[a-z]\w*$#iD', $name)) {
1✔
391
                        throw new \LogicException("Invalid provider name '$name'.");
×
392
                }
393

394
                $this->providers->$name = $provider;
1✔
395
                return $this;
1✔
396
        }
397

398

399
        /**
400
         * Returns all providers.
401
         * @return mixed[]
402
         */
403
        public function getProviders(): array
404
        {
405
                return (array) $this->providers;
1✔
406
        }
407

408

409
        public function setPolicy(?Policy $policy): static
1✔
410
        {
411
                $this->policy = $policy;
1✔
412
                return $this;
1✔
413
        }
414

415

416
        public function getPolicy(bool $effective = false): ?Policy
1✔
417
        {
418
                return !$effective || $this->sandboxed
1✔
419
                        ? $this->policy
1✔
420
                        : null;
1✔
421
        }
422

423

424
        public function setExceptionHandler(callable $handler): static
1✔
425
        {
426
                $this->providers->coreExceptionHandler = $handler;
1✔
427
                return $this;
1✔
428
        }
429

430

431
        public function setSandboxMode(bool $state = true): static
1✔
432
        {
433
                $this->sandboxed = $state;
1✔
434
                return $this;
1✔
435
        }
436

437

438
        public function setContentType(string $type): static
1✔
439
        {
440
                $this->contentType = $type;
1✔
441
                return $this;
1✔
442
        }
443

444

445
        /**
446
         * Sets path to temporary directory.
447
         */
448
        public function setTempDirectory(?string $path): static
1✔
449
        {
450
                $this->cache->directory = $path;
1✔
451
                return $this;
1✔
452
        }
453

454

455
        /**
456
         * Sets auto-refresh mode.
457
         */
458
        public function setAutoRefresh(bool $state = true): static
459
        {
460
                $this->cache->autoRefresh = $state;
×
461
                return $this;
×
462
        }
463

464

465
        /**
466
         * Enables declare(strict_types=1) in templates.
467
         */
468
        public function setStrictTypes(bool $state = true): static
1✔
469
        {
470
                $this->strictTypes = $state;
1✔
471
                return $this;
1✔
472
        }
473

474

475
        public function setStrictParsing(bool $state = true): static
1✔
476
        {
477
                $this->strictParsing = $state;
1✔
478
                return $this;
1✔
479
        }
480

481

482
        public function isStrictParsing(): bool
483
        {
484
                return $this->strictParsing;
1✔
485
        }
486

487

488
        /**
489
         * Sets the locale. It uses the same identifiers as the PHP intl extension.
490
         */
491
        public function setLocale(?string $locale): static
492
        {
493
                if ($locale && !extension_loaded('intl')) {
×
494
                        throw new RuntimeException("Setting a locale requires the 'intl' extension to be installed.");
×
495
                }
496
                $this->locale = $locale;
×
497
                return $this;
×
498
        }
499

500

501
        public function getLocale(): ?string
502
        {
503
                return $this->locale;
1✔
504
        }
505

506

507
        public function setLoader(Loader $loader): static
1✔
508
        {
509
                $this->loader = $loader;
1✔
510
                return $this;
1✔
511
        }
512

513

514
        public function getLoader(): Loader
515
        {
516
                return $this->loader ??= new Loaders\FileLoader;
1✔
517
        }
518

519

520
        public function enablePhpLinter(?string $phpBinary): static
521
        {
522
                $this->phpBinary = $phpBinary;
×
523
                return $this;
×
524
        }
525

526

527
        /**
528
         * Sets default Latte syntax. Available options: 'single', 'double', 'off'
529
         */
530
        public function setSyntax(string $syntax): static
1✔
531
        {
532
                $this->syntax = $syntax;
1✔
533
                return $this;
1✔
534
        }
535

536

537
        /**
538
         * @param  object|mixed[]  $params
539
         * @return mixed[]
540
         */
541
        private function processParams(object|array $params): array
1✔
542
        {
543
                if (is_array($params)) {
1✔
544
                        return $params;
1✔
545
                }
546

547
                $rc = new \ReflectionClass($params);
1✔
548
                $methods = $rc->getMethods(\ReflectionMethod::IS_PUBLIC);
1✔
549
                foreach ($methods as $method) {
1✔
550
                        if ($method->getAttributes(Attributes\TemplateFilter::class)) {
1✔
551
                                $this->addFilter($method->name, [$params, $method->name]);
1✔
552
                        }
553

554
                        if ($method->getAttributes(Attributes\TemplateFunction::class)) {
1✔
555
                                $this->addFunction($method->name, [$params, $method->name]);
1✔
556
                        }
557

558
                        if (strpos((string) $method->getDocComment(), '@filter')) {
1✔
559
                                trigger_error('Annotation @filter is deprecated, use attribute #[Latte\Attributes\TemplateFilter]');
×
560
                                $this->addFilter($method->name, [$params, $method->name]);
×
561
                        }
562

563
                        if (strpos((string) $method->getDocComment(), '@function')) {
1✔
564
                                trigger_error('Annotation @function is deprecated, use attribute #[Latte\Attributes\TemplateFunction]');
×
565
                                $this->addFunction($method->name, [$params, $method->name]);
×
566
                        }
567
                }
568

569
                $res = get_object_vars($params);
1✔
570
                if (PHP_VERSION_ID >= 80400) {
1✔
571
                        foreach ($rc->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
×
572
                                if ($property->isVirtual() && $property->hasHook(\PropertyHookType::Get)) {
×
573
                                        $name = $property->getName();
×
574
                                        $res[$name] = $params->$name;
×
575
                                }
576
                        }
577
                }
578

579
                return $res;
1✔
580
        }
581

582

583
        public function __get(string $name)
584
        {
585
                if ($name === 'onCompile') {
×
586
                        $trace = debug_backtrace(0)[0];
×
587
                        $loc = isset($trace['file'], $trace['line'])
×
588
                                ? ' (in ' . $trace['file'] . ' on ' . $trace['line'] . ')'
×
589
                                : '';
×
590
                        throw new \LogicException('You use Latte 3 together with the code designed for Latte 2' . $loc);
×
591
                }
592
        }
593
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc