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

nette / latte / 23219673715

17 Mar 2026 10:36PM UTC coverage: 94.974% (+0.002%) from 94.972%
23219673715

push

github

dg
added Feature::ScopedLoopVariables

25 of 25 new or added lines in 2 files covered. (100.0%)

26 existing lines in 3 files now uncovered.

5612 of 5909 relevant lines covered (94.97%)

0.95 hits per line

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

87.86
/src/Latte/Engine.php
1
<?php declare(strict_types=1);
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
namespace Latte;
9

10
use Latte\Compiler\Nodes\TemplateNode;
11
use function array_map, array_merge, class_exists, extension_loaded, get_debug_type, preg_match, serialize, substr;
12

13

14
/**
15
 * Templating engine Latte.
16
 */
17
class Engine
18
{
19
        public const Version = '3.1.2';
20
        public const VersionId = 30102;
21

22
        /** @deprecated use Engine::Version */
23
        public const
24
                VERSION = self::Version,
25
                VERSION_ID = self::VersionId;
26

27
        #[\Deprecated('use Latte\ContentType::Html')]
28
        public const CONTENT_HTML = ContentType::Html;
29

30
        #[\Deprecated('use Latte\ContentType::Xml')]
31
        public const CONTENT_XML = ContentType::Xml;
32

33
        #[\Deprecated('use Latte\ContentType::JavaScript')]
34
        public const CONTENT_JS = ContentType::JavaScript;
35

36
        #[\Deprecated('use Latte\ContentType::Css')]
37
        public const CONTENT_CSS = ContentType::Css;
38

39
        #[\Deprecated('use Latte\ContentType::ICal')]
40
        public const CONTENT_ICAL = ContentType::ICal;
41

42
        #[\Deprecated('use Latte\ContentType::Text')]
43
        public const CONTENT_TEXT = ContentType::Text;
44

45
        private ?Loader $loader = null;
46
        private Runtime\FilterExecutor $filters;
47
        private Runtime\FunctionExecutor $functions;
48
        private \stdClass $providers;
49

50
        /** @var Extension[] */
51
        private array $extensions = [];
52
        private string $contentType = ContentType::Html;
53
        private Runtime\Cache $cache;
54

55
        /** @var array<string, bool> */
56
        private array $features = [
57
                Feature::StrictTypes->name => true,
58
        ];
59

60
        private ?Policy $policy = null;
61
        private bool $sandboxed = false;
62
        private ?string $phpBinary = null;
63
        private ?string $configurationHash;
64
        private ?string $locale = null;
65
        private ?string $syntax = null;
66

67

68
        public function __construct()
69
        {
70
                $this->cache = new Runtime\Cache;
1✔
71
                $this->filters = new Runtime\FilterExecutor;
1✔
72
                $this->functions = new Runtime\FunctionExecutor;
1✔
73
                $this->providers = new \stdClass;
1✔
74
                $this->addDefaultExtensions();
1✔
75
        }
1✔
76

77

78
        /**
79
         * Renders template to output.
80
         * @param  object|mixed[]  $params
81
         */
82
        public function render(string $name, object|array $params = [], ?string $block = null): void
1✔
83
        {
84
                $template = $this->createTemplate($name, Helpers::resolveParams($this, $params));
1✔
85
                $template->global->coreCaptured = false;
1✔
86
                $template->render($block);
1✔
87
        }
1✔
88

89

90
        /**
91
         * Renders template to string.
92
         * @param  object|mixed[]  $params
93
         */
94
        public function renderToString(string $name, object|array $params = [], ?string $block = null): string
1✔
95
        {
96
                $template = $this->createTemplate($name, Helpers::resolveParams($this, $params));
1✔
97
                $template->global->coreCaptured = true;
1✔
98
                return $template->capture(fn() => $template->render($block));
1✔
99
        }
100

101

102
        /**
103
         * Creates template object.
104
         * @param  mixed[]  $params
105
         */
106
        public function createTemplate(string $name, array $params = [], bool $clearCache = true): Runtime\Template
1✔
107
        {
108
                $this->configurationHash = $clearCache ? null : $this->configurationHash;
1✔
109
                $class = $this->loadTemplate($name);
1✔
110
                $this->providers->fn = $this->functions;
1✔
111
                return new $class(
1✔
112
                        $this,
1✔
113
                        $params,
114
                        $this->filters,
1✔
115
                        $this->providers,
1✔
116
                        $name,
117
                );
118
        }
119

120

121
        /**
122
         * Compiles template to PHP code.
123
         */
124
        public function compile(string $name): string
1✔
125
        {
126
                if ($this->sandboxed && !$this->policy) {
1✔
127
                        throw new \LogicException('In sandboxed mode you need to set a security policy.');
1✔
128
                }
129

130
                $template = $this->getLoader()->getContent($name);
1✔
131

132
                try {
133
                        $node = $this->parse($template);
1✔
134
                        $this->applyPasses($node);
1✔
135
                        $compiled = $this->generate($node, $name);
1✔
136

137
                } catch (\Throwable $e) {
1✔
138
                        if (!$e instanceof CompileException && !$e instanceof SecurityViolationException) {
1✔
139
                                $e = new CompileException("Thrown exception '{$e->getMessage()}'", previous: $e);
1✔
140
                        }
141

142
                        throw $e->setSource($template, $name);
1✔
143
                }
144

145
                if ($this->phpBinary) {
1✔
UNCOV
146
                        Compiler\PhpHelpers::checkCode($this->phpBinary, $compiled, "(compiled $name)");
×
147
                }
148

149
                return $compiled;
1✔
150
        }
151

152

153
        /**
154
         * Parses template to AST node.
155
         */
156
        public function parse(string $template): TemplateNode
1✔
157
        {
158
                $parser = new Compiler\TemplateParser;
1✔
159
                $parser->getLexer()->setSyntax($this->syntax);
1✔
160
                $parser->strict = $this->hasFeature(Feature::StrictParsing);
1✔
161

162
                foreach ($this->extensions as $extension) {
1✔
163
                        $extension->beforeCompile($this);
1✔
164
                        $parser->addTags($extension->getTags());
1✔
165
                }
166

167
                return $parser
168
                        ->setContentType($this->contentType)
1✔
169
                        ->setPolicy($this->getPolicy(effective: true))
1✔
170
                        ->parse($template);
1✔
171
        }
172

173

174
        /**
175
         * Runs all registered compiler passes over the AST.
176
         */
177
        public function applyPasses(TemplateNode &$node): void
1✔
178
        {
179
                $passes = [];
1✔
180
                foreach ($this->extensions as $extension) {
1✔
181
                        $passes = array_merge($passes, $extension->getPasses());
1✔
182
                }
183

184
                $passes = Helpers::sortBeforeAfter($passes);
1✔
185
                foreach ($passes as $pass) {
1✔
186
                        $pass = $pass instanceof \stdClass ? $pass->subject : $pass;
1✔
187
                        ($pass)($node);
1✔
188
                }
189
        }
1✔
190

191

192
        /**
193
         * Generates compiled PHP code.
194
         */
195
        public function generate(TemplateNode $node, string $name): string
1✔
196
        {
197
                $generator = new Compiler\TemplateGenerator;
1✔
198
                $generator->buildClass($node, $this->features);
1✔
199
                return $generator->generateCode($this->getTemplateClass($name), $name, $this->hasFeature(Feature::StrictTypes));
1✔
200
        }
201

202

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

213
                $this->loadTemplate($name);
1✔
214
        }
1✔
215

216

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

235

236
        /**
237
         * Returns the file path where compiled template will be cached.
238
         */
239
        public function getCacheFile(string $name): string
1✔
240
        {
241
                return $this->cache->generateFilePath($this, $name);
1✔
242
        }
243

244

245
        /**
246
         * Returns the PHP class name for compiled template.
247
         */
248
        public function getTemplateClass(string $name): string
1✔
249
        {
250
                return 'Template_' . $this->generateTemplateHash($name);
1✔
251
        }
252

253

254
        /**
255
         * Generates unique hash for template based on current configuration.
256
         * Used to create isolated cache files for different engine configurations.
257
         * @internal
258
         */
259
        public function generateTemplateHash(string $name): string
1✔
260
        {
261
                $hash = $this->configurationHash ?? hash('xxh128', serialize($this->generateConfigurationSignature()));
1✔
262
                $hash .= $this->getLoader()->getUniqueId($name);
1✔
263
                return substr(hash('xxh128', $hash), 0, 10);
1✔
264
        }
265

266

267
        /**
268
         * Returns values that determine isolation for different configurations.
269
         * When any of these values change, a new compiled template is created to avoid conflicts.
270
         * @return list<mixed>
271
         */
272
        protected function generateConfigurationSignature(): array
273
        {
274
                return [
275
                        $this->contentType,
1✔
276
                        $this->features,
1✔
277
                        $this->syntax,
1✔
278
                        array_map(
1✔
279
                                fn($extension) => [get_debug_type($extension), $extension->getCacheKey($this)],
1✔
280
                                $this->extensions,
1✔
281
                        ),
282
                ];
283
        }
284

285

286
        /**
287
         * Registers run-time filter.
288
         */
289
        public function addFilter(string $name, callable $callback): static
1✔
290
        {
291
                if (!preg_match('#^[a-z]\w*$#iD', $name)) {
1✔
UNCOV
292
                        throw new \LogicException("Invalid filter name '$name'.");
×
293
                }
294

295
                $this->filters->add($name, $callback);
1✔
296
                return $this;
1✔
297
        }
298

299

300
        #[\Deprecated('Use addFilter() instead.')]
301
        public function addFilterLoader(callable $loader): static
1✔
302
        {
303
                trigger_error('Filter loader is deprecated, use addFilter() instead.', E_USER_DEPRECATED);
1✔
304
                $this->filters->add(null, $loader);
1✔
305
                return $this;
1✔
306
        }
307

308

309
        /**
310
         * Returns all run-time filters.
311
         * @return array<string, callable>
312
         */
313
        public function getFilters(): array
314
        {
315
                return $this->filters->getAll();
1✔
316
        }
317

318

319
        /**
320
         * Calls a run-time filter.
321
         * @param  mixed[]  $args
322
         */
323
        public function invokeFilter(string $name, array $args): mixed
1✔
324
        {
325
                return ($this->filters->$name)(...$args);
1✔
326
        }
327

328

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

339
                foreach ($extension->getFunctions() as $name => $value) {
1✔
340
                        $this->functions->add($name, $value);
1✔
341
                }
342

343
                foreach ($extension->getProviders() as $name => $value) {
1✔
UNCOV
344
                        $this->providers->$name = $value;
×
345
                }
346
                return $this;
1✔
347
        }
348

349

350
        /** @return list<Extension> */
351
        public function getExtensions(): array
352
        {
353
                return array_values($this->extensions);
1✔
354
        }
355

356

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

366
                $this->functions->add($name, $callback);
1✔
367
                return $this;
1✔
368
        }
369

370

371
        /**
372
         * Calls a run-time function.
373
         * @param  mixed[]  $args
374
         */
375
        public function invokeFunction(string $name, array $args): mixed
1✔
376
        {
377
                return ($this->functions->$name)(null, ...$args);
1✔
378
        }
379

380

381
        /**
382
         * Returns all run-time functions.
383
         * @return array<string, callable>
384
         */
385
        public function getFunctions(): array
386
        {
387
                return $this->functions->getAll();
1✔
388
        }
389

390

391
        /**
392
         * Adds new provider.
393
         */
394
        public function addProvider(string $name, mixed $provider): static
1✔
395
        {
396
                if (!preg_match('#^[a-z]\w*$#iD', $name)) {
1✔
UNCOV
397
                        throw new \LogicException("Invalid provider name '$name'.");
×
398
                }
399

400
                $this->providers->$name = $provider;
1✔
401
                return $this;
1✔
402
        }
403

404

405
        /**
406
         * Returns all providers.
407
         * @return array<string, mixed>
408
         */
409
        public function getProviders(): array
410
        {
411
                return (array) $this->providers;
1✔
412
        }
413

414

415
        public function setPolicy(?Policy $policy): static
1✔
416
        {
417
                $this->policy = $policy;
1✔
418
                return $this;
1✔
419
        }
420

421

422
        public function getPolicy(bool $effective = false): ?Policy
1✔
423
        {
424
                return !$effective || $this->sandboxed
1✔
425
                        ? $this->policy
1✔
426
                        : null;
1✔
427
        }
428

429

430
        /**
431
         * Sets a handler called when an exception occurs during template rendering.
432
         */
433
        public function setExceptionHandler(callable $handler): static
1✔
434
        {
435
                $this->providers->coreExceptionHandler = $handler(...);
1✔
436
                return $this;
1✔
437
        }
438

439

440
        public function setSandboxMode(bool $state = true): static
1✔
441
        {
442
                $this->sandboxed = $state;
1✔
443
                return $this;
1✔
444
        }
445

446

447
        public function setContentType(string $type): static
1✔
448
        {
449
                $this->contentType = $type;
1✔
450
                return $this;
1✔
451
        }
452

453

454
        /**
455
         * Sets path to cache directory.
456
         */
457
        public function setCacheDirectory(?string $path): static
1✔
458
        {
459
                $this->cache->directory = $path;
1✔
460
                return $this;
1✔
461
        }
462

463

464
        /** @deprecated use setCacheDirectory() instead */
465
        public function setTempDirectory(?string $path): static
466
        {
UNCOV
467
                return $this->setCacheDirectory($path);
×
468
        }
469

470

471
        /**
472
         * Sets auto-refresh mode.
473
         */
474
        public function setAutoRefresh(bool $state = true): static
475
        {
UNCOV
476
                $this->cache->autoRefresh = $state;
×
UNCOV
477
                return $this;
×
478
        }
479

480

481
        /**
482
         * Enables or disables an engine feature.
483
         */
484
        public function setFeature(Feature $feature, bool $state = true): static
1✔
485
        {
486
                $this->features[$feature->name] = $state;
1✔
487
                return $this;
1✔
488
        }
489

490

491
        /**
492
         * Checks if a feature is enabled.
493
         */
494
        public function hasFeature(Feature $feature): bool
1✔
495
        {
496
                return $this->features[$feature->name] ?? false;
1✔
497
        }
498

499

500
        /**
501
         * Enables declare(strict_types=1) in templates.
502
         * @deprecated use setFeature(Feature::StrictTypes, ...) instead
503
         */
504
        public function setStrictTypes(bool $state = true): static
505
        {
UNCOV
506
                return $this->setFeature(Feature::StrictTypes, $state);
×
507
        }
508

509

510
        /** @deprecated use setFeature(Feature::StrictParsing, ...) instead */
511
        public function setStrictParsing(bool $state = true): static
512
        {
UNCOV
513
                return $this->setFeature(Feature::StrictParsing, $state);
×
514
        }
515

516

517
        /** @deprecated use hasFeature(Feature::StrictParsing) instead */
518
        public function isStrictParsing(): bool
519
        {
UNCOV
520
                return $this->hasFeature(Feature::StrictParsing);
×
521
        }
522

523

524
        /**
525
         * Sets the locale. It uses the same identifiers as the PHP intl extension.
526
         */
527
        public function setLocale(?string $locale): static
528
        {
UNCOV
529
                if ($locale && !extension_loaded('intl')) {
×
UNCOV
530
                        throw new RuntimeException("Setting a locale requires the 'intl' extension to be installed.");
×
531
                }
532
                $this->locale = $locale;
×
UNCOV
533
                return $this;
×
534
        }
535

536

537
        public function getLocale(): ?string
538
        {
539
                return $this->locale;
1✔
540
        }
541

542

543
        public function setLoader(Loader $loader): static
1✔
544
        {
545
                $this->loader = $loader;
1✔
546
                return $this;
1✔
547
        }
548

549

550
        public function getLoader(): Loader
551
        {
552
                return $this->loader ??= new Loaders\FileLoader;
1✔
553
        }
554

555

556
        /**
557
         * Validates compiled PHP code using the given PHP binary. Pass null to disable.
558
         */
559
        public function enablePhpLinter(?string $phpBinary): static
560
        {
UNCOV
561
                $this->phpBinary = $phpBinary;
×
UNCOV
562
                return $this;
×
563
        }
564

565

566
        /**
567
         * Sets default Latte syntax. Available options: 'single', 'double', 'off'
568
         */
569
        public function setSyntax(string $syntax): static
1✔
570
        {
571
                $this->syntax = $syntax;
1✔
572
                return $this;
1✔
573
        }
574

575

576
        /** @deprecated use setFeature(Feature::MigrationWarnings, ...) instead */
577
        public function setMigrationWarnings(bool $state = true): static
578
        {
UNCOV
579
                return $this->setFeature(Feature::MigrationWarnings, $state);
×
580
        }
581

582

583
        protected function addDefaultExtensions(): void
584
        {
585
                $this->addExtension(new Essential\CoreExtension);
1✔
586
                $this->addExtension(new Sandbox\SandboxExtension);
1✔
587
        }
1✔
588
}
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