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