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

nette / latte / 19616469167

23 Nov 2025 07:55PM UTC coverage: 94.717% (+0.09%) from 94.624%
19616469167

push

github

dg
Released version 3.1.0

5379 of 5679 relevant lines covered (94.72%)

0.95 hits per line

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

89.42
/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, get_debug_type, get_object_vars, is_array, preg_match, serialize, substr;
14
use const PHP_VERSION_ID;
15

16

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

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

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

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

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

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

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

45
        #[\Deprecated('use Latte\ContentType::Text')]
46
        public const CONTENT_TEXT = ContentType::Text;
47

48
        private ?Loader $loader = null;
49
        private Runtime\FilterExecutor $filters;
50
        private Runtime\FunctionExecutor $functions;
51
        private \stdClass $providers;
52

53
        /** @var Extension[] */
54
        private array $extensions = [];
55
        private string $contentType = ContentType::Html;
56
        private Cache $cache;
57
        private bool $strictTypes = true;
58
        private bool $strictParsing = false;
59
        private ?Policy $policy = null;
60
        private bool $sandboxed = false;
61
        private ?string $phpBinary = null;
62
        private ?string $configurationHash;
63
        private ?string $locale = null;
64
        private ?string $syntax = null;
65
        private bool $migrationWarnings = false;
66

67

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

78

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

90

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

102

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

121

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

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

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

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

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

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

150
                return $compiled;
1✔
151
        }
152

153

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

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

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

174

175
        /**
176
         * Calls node visitors.
177
         */
178
        public function applyPasses(TemplateNode &$node): void
1✔
179
        {
180
                $passes = [];
1✔
181
                foreach ($this->extensions as $extension) {
1✔
182
                        $passes = array_merge($passes, $extension->getPasses());
1✔
183
                }
184

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

192

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

203

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

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

217

218
        private function loadTemplate(string $name): string
1✔
219
        {
220
                $class = $this->getTemplateClass($name);
1✔
221
                if (class_exists($class, 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✔
228
                                throw (new CompileException('Error in template: ' . error_get_last()['message']))
×
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
         */
271
        protected function generateConfigurationSignature(): array
272
        {
273
                return [
274
                        $this->contentType,
1✔
275
                        $this->strictTypes,
1✔
276
                        $this->strictParsing,
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✔
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 callable[]
312
         */
313
        public function getFilters(): array
314
        {
315
                return $this->filters->getAll();
1✔
316
        }
317

318

319
        /**
320
         * Call 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✔
344
                        $this->providers->$name = $value;
×
345
                }
346
                return $this;
1✔
347
        }
348

349

350
        /** @return Extension[] */
351
        public function getExtensions(): array
352
        {
353
                return $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✔
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
         * Call 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
         * @return callable[]
383
         */
384
        public function getFunctions(): array
385
        {
386
                return $this->functions->getAll();
1✔
387
        }
388

389

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

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

403

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

413

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

420

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

428

429
        public function setExceptionHandler(callable $handler): static
1✔
430
        {
431
                $this->providers->coreExceptionHandler = $handler;
1✔
432
                return $this;
1✔
433
        }
434

435

436
        public function setSandboxMode(bool $state = true): static
1✔
437
        {
438
                $this->sandboxed = $state;
1✔
439
                return $this;
1✔
440
        }
441

442

443
        public function setContentType(string $type): static
1✔
444
        {
445
                $this->contentType = $type;
1✔
446
                return $this;
1✔
447
        }
448

449

450
        /**
451
         * Sets path to temporary directory.
452
         */
453
        public function setTempDirectory(?string $path): static
1✔
454
        {
455
                $this->cache->directory = $path;
1✔
456
                return $this;
1✔
457
        }
458

459

460
        /**
461
         * Sets auto-refresh mode.
462
         */
463
        public function setAutoRefresh(bool $state = true): static
464
        {
465
                $this->cache->autoRefresh = $state;
×
466
                return $this;
×
467
        }
468

469

470
        /**
471
         * Enables declare(strict_types=1) in templates.
472
         */
473
        public function setStrictTypes(bool $state = true): static
1✔
474
        {
475
                $this->strictTypes = $state;
1✔
476
                return $this;
1✔
477
        }
478

479

480
        public function setStrictParsing(bool $state = true): static
1✔
481
        {
482
                $this->strictParsing = $state;
1✔
483
                return $this;
1✔
484
        }
485

486

487
        public function isStrictParsing(): bool
488
        {
489
                return $this->strictParsing;
1✔
490
        }
491

492

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

505

506
        public function getLocale(): ?string
507
        {
508
                return $this->locale;
1✔
509
        }
510

511

512
        public function setLoader(Loader $loader): static
1✔
513
        {
514
                $this->loader = $loader;
1✔
515
                return $this;
1✔
516
        }
517

518

519
        public function getLoader(): Loader
520
        {
521
                return $this->loader ??= new Loaders\FileLoader;
1✔
522
        }
523

524

525
        public function enablePhpLinter(?string $phpBinary): static
526
        {
527
                $this->phpBinary = $phpBinary;
×
528
                return $this;
×
529
        }
530

531

532
        /**
533
         * Sets default Latte syntax. Available options: 'single', 'double', 'off'
534
         */
535
        public function setSyntax(string $syntax): static
1✔
536
        {
537
                $this->syntax = $syntax;
1✔
538
                return $this;
1✔
539
        }
540

541

542
        public function setMigrationWarnings(bool $state = true): static
1✔
543
        {
544
                $this->migrationWarnings = $state;
1✔
545
                return $this;
1✔
546
        }
547

548

549
        /**
550
         * @param  object|mixed[]  $params
551
         * @return mixed[]
552
         */
553
        private function processParams(object|array $params): array
1✔
554
        {
555
                if (is_array($params)) {
1✔
556
                        return $params;
1✔
557
                }
558

559
                $rc = new \ReflectionClass($params);
1✔
560
                $methods = $rc->getMethods(\ReflectionMethod::IS_PUBLIC);
1✔
561
                foreach ($methods as $method) {
1✔
562
                        if ($method->getAttributes(Attributes\TemplateFilter::class)) {
1✔
563
                                $this->addFilter($method->name, [$params, $method->name]);
1✔
564
                        }
565

566
                        if ($method->getAttributes(Attributes\TemplateFunction::class)) {
1✔
567
                                $this->addFunction($method->name, [$params, $method->name]);
1✔
568
                        }
569
                }
570

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

581
                return $res;
1✔
582
        }
583
}
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