Passed
Push — master ( 7b7005...55ec05 )
by Brent
02:29
created

TwigEngine::getTemplateExtension()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Brendt\Stitcher\Template\Twig;
4
5
use Brendt\Stitcher\Template\TemplateEngine;
6
use Brendt\Stitcher\Template\TemplatePlugin;
7
use Symfony\Component\Finder\SplFileInfo;
8
use Twig_Environment;
9
use Twig_Loader_Filesystem;
10
11
/**
12
 * The Twig template engine.
13
 */
14
class TwigEngine extends Twig_Environment implements TemplateEngine
15
{
16
    private $variables = [];
17
18
    public function __construct(string $templateDir, TemplatePlugin $templatePlugin) {
19
        $loader = new Twig_Loader_Filesystem($templateDir);
20
21
        parent::__construct($loader, [
22
            'cache' => false,
23
        ]);
24
25
        $this->addFunction(new \Twig_SimpleFunction('meta', [$templatePlugin, 'meta'], ['is_safe' => ['html'],]));
26
        $this->addFunction(new \Twig_SimpleFunction('css', [$templatePlugin, 'css'], ['is_safe' => ['html'],]));
27
        $this->addFunction(new \Twig_SimpleFunction('js', [$templatePlugin, 'js'], ['is_safe' => ['html'],]));
28
        $this->addFunction(new \Twig_SimpleFunction('image', [$templatePlugin, 'image']));
29
        $this->addFunction(new \Twig_SimpleFunction('file', [$templatePlugin, 'file']));
30
    }
31
32
    public function renderTemplate(SplFileInfo $template) {
33
        return $this->render($template->getRelativePathname(), $this->variables);
34
    }
35
36
    public function addTemplateVariables(array $variables) {
37
        $this->variables += $variables;
38
39
        return $this;
40
    }
41
42
    public function hasTemplateVariable(string $name) : bool {
43
        return isset($this->variables[$name]);
44
    }
45
46
    public function clearTemplateVariables() {
47
        $this->variables = [];
48
49
        return $this;
50
    }
51
52
    public function addTemplateVariable($name, $value) {
53
        $this->variables[$name] = $value;
54
55
        return $this;
56
    }
57
58
    public function clearTemplateVariable($variable) {
59
        unset($this->variables[$variable]);
60
61
        return $this;
62
    }
63
64
    public function getTemplateExtensions(): array {
65
        return ['html', 'twig'];
66
    }
67
}
68