1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Nette\Bridges\ApplicationDI;
9:
10: use Nette;
11: use Latte;
12:
13:
14: 15: 16:
17: class LatteExtension extends Nette\DI\CompilerExtension
18: {
19: public $defaults = [
20: 'xhtml' => FALSE,
21: 'macros' => [],
22: ];
23:
24:
25: private $debugMode;
26:
27:
28: private $tempDir;
29:
30:
31: public function __construct($tempDir, $debugMode = FALSE)
32: {
33: $this->tempDir = $tempDir;
34: $this->debugMode = $debugMode;
35: }
36:
37:
38: public function loadConfiguration()
39: {
40: if (!class_exists(Latte\Engine::class)) {
41: return;
42: }
43:
44: $config = $this->validateConfig($this->defaults);
45: $builder = $this->getContainerBuilder();
46:
47: $builder->addDefinition($this->prefix('latteFactory'))
48: ->setClass(Latte\Engine::class)
49: ->addSetup('setTempDirectory', [$this->tempDir])
50: ->addSetup('setAutoRefresh', [$this->debugMode])
51: ->addSetup('setContentType', [$config['xhtml'] ? Latte\Compiler::CONTENT_XHTML : Latte\Compiler::CONTENT_HTML])
52: ->addSetup('Nette\Utils\Html::$xhtml = ?', [(bool) $config['xhtml']])
53: ->setImplement(Nette\Bridges\ApplicationLatte\ILatteFactory::class);
54:
55: $builder->addDefinition($this->prefix('templateFactory'))
56: ->setClass(Nette\Application\UI\ITemplateFactory::class)
57: ->setFactory(Nette\Bridges\ApplicationLatte\TemplateFactory::class);
58:
59: foreach ($config['macros'] as $macro) {
60: if (strpos($macro, '::') === FALSE && class_exists($macro)) {
61: $macro .= '::install';
62: }
63: $this->addMacro($macro);
64: }
65:
66: if ($this->name === 'latte') {
67: $builder->addAlias('nette.latteFactory', $this->prefix('latteFactory'));
68: $builder->addAlias('nette.templateFactory', $this->prefix('templateFactory'));
69: }
70: }
71:
72:
73: 74: 75: 76:
77: public function addMacro(callable $macro)
78: {
79: $builder = $this->getContainerBuilder();
80: $builder->getDefinition($this->prefix('latteFactory'))
81: ->addSetup('?->onCompile[] = function ($engine) { ' . $macro . '($engine->getCompiler()); }', ['@self']);
82: }
83:
84: }
85: