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

nette / latte / 16737240550

05 Aug 2025 12:19AM UTC coverage: 93.791% (-0.02%) from 93.814%
16737240550

push

github

dg
support for PHP 8.5

5242 of 5589 relevant lines covered (93.79%)

0.94 hits per line

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

83.59
/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.23';
23
        public const VersionId = 30023;
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

56

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

67

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

79

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

91

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

110

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

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

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

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

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

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

139
                return $compiled;
1✔
140
        }
141

142

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

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

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

162

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

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

180

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

195

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

206
                $this->loadTemplate($name);
1✔
207
        }
1✔
208

209

210
        private function loadTemplate(string $name): string
1✔
211
        {
212
                $class = $this->getTemplateClass($name);
1✔
213
                if (class_exists($class, false)) {
1✔
214
                        // nothing
215
                } elseif ($this->cache->directory) {
1✔
216
                        $this->cache->loadOrCreate($this, $name);
1✔
217
                } else {
218
                        $compiled = $this->compile($name);
1✔
219
                        if (@eval(substr($compiled, 5)) === false) { // @ is escalated to exception, substr removes <?php
1✔
220
                                throw new CompileException(
×
221
                                        'Error in template: ' . error_get_last()['message'],
×
222
                                        new SourceReference("$name (compiled)", code: $compiled),
×
223
                                );
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
                        array_map(
1✔
272
                                fn($extension) => [get_debug_type($extension), $extension->getCacheKey($this)],
1✔
273
                                $this->extensions,
1✔
274
                        ),
275
                ];
276
        }
277

278

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

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

292

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

302

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

312

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

322

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

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

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

343

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

350

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

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

364

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

374

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

383

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

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

397

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

407

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

414

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

422

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

429

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

436

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

443

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

453

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

463

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

473

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

480

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

486

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

499

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

505

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

512

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

518

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

525

526
        /**
527
         * @param  object|mixed[]  $params
528
         * @return mixed[]
529
         */
530
        private function processParams(object|array $params): array
1✔
531
        {
532
                if (is_array($params)) {
1✔
533
                        return $params;
1✔
534
                }
535

536
                $rc = new \ReflectionClass($params);
1✔
537
                $methods = $rc->getMethods(\ReflectionMethod::IS_PUBLIC);
1✔
538
                foreach ($methods as $method) {
1✔
539
                        if ($method->getAttributes(Attributes\TemplateFilter::class)) {
1✔
540
                                $this->addFilter($method->name, [$params, $method->name]);
1✔
541
                        }
542

543
                        if ($method->getAttributes(Attributes\TemplateFunction::class)) {
1✔
544
                                $this->addFunction($method->name, [$params, $method->name]);
1✔
545
                        }
546

547
                        if (strpos((string) $method->getDocComment(), '@filter')) {
1✔
548
                                trigger_error('Annotation @filter is deprecated, use attribute #[Latte\Attributes\TemplateFilter]');
×
549
                                $this->addFilter($method->name, [$params, $method->name]);
×
550
                        }
551

552
                        if (strpos((string) $method->getDocComment(), '@function')) {
1✔
553
                                trigger_error('Annotation @function is deprecated, use attribute #[Latte\Attributes\TemplateFunction]');
×
554
                                $this->addFunction($method->name, [$params, $method->name]);
×
555
                        }
556
                }
557

558
                $res = get_object_vars($params);
1✔
559
                if (PHP_VERSION_ID >= 80400) {
1✔
560
                        foreach ($rc->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
×
561
                                if ($property->isVirtual() && $property->hasHook(\PropertyHookType::Get)) {
×
562
                                        $name = $property->getName();
×
563
                                        $res[$name] = $params->$name;
×
564
                                }
565
                        }
566
                }
567

568
                return $res;
1✔
569
        }
570

571

572
        public function __get(string $name)
573
        {
574
                if ($name === 'onCompile') {
×
575
                        $trace = debug_backtrace(0)[0];
×
576
                        $loc = isset($trace['file'], $trace['line'])
×
577
                                ? ' (in ' . $trace['file'] . ' on ' . $trace['line'] . ')'
×
578
                                : '';
×
579
                        throw new \LogicException('You use Latte 3 together with the code designed for Latte 2' . $loc);
×
580
                }
581
        }
582
}
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