Completed
Push — develop ( 7b6eba...aad3df )
by Jens
03:19
created

HandlebarsEnvironment::render()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 5
Bugs 1 Features 2
Metric Value
c 5
b 1
f 2
dl 0
loc 11
ccs 7
cts 7
cp 1
rs 9.4285
cc 1
eloc 7
nc 1
nop 2
crap 1
1
<?php
2
/**
3
 * @author @jayS-de <[email protected]>
4
 */
5
6
7
namespace JaySDe\HandlebarsBundle;
8
9
10
use JaySDe\HandlebarsBundle\Cache\Filesystem;
11
use JaySDe\HandlebarsBundle\Error\LoaderException;
12
use JaySDe\HandlebarsBundle\Loader\FilesystemLoader;
13
use LightnCandy\LightnCandy;
14
use Symfony\Component\Config\Resource\FileResource;
15
16
class HandlebarsEnvironment
17
{
18
    protected $options;
19
20
    /**
21
     * @var Filesystem
22
     */
23
    protected $cache;
24
    /**
25
     * @var FilesystemLoader
26
     */
27
    protected $loader;
28
29
    protected $extensions = [];
30
    protected $autoReload;
31
    protected $debug;
32
    private $profiler;
33
34
    private $helper;
35
36 11
    public function __construct(
37
        FilesystemLoader $loader,
38
        HandlebarsHelper $helper,
39
        $options = [],
40
        Filesystem $cache,
41
        HandlebarsProfileExtension $profiler
42
    )
43
    {
44 11
        $this->loader = $loader;
45 11
        $this->partials = $partials = new \ArrayObject();
0 ignored issues
show
Bug introduced by
The property partials does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
46 11
        $this->helper = $helper;
47 11
        $flags = (LightnCandy::FLAG_BESTPERFORMANCE |
48 11
            LightnCandy::FLAG_HANDLEBARSJS |
49 11
            LightnCandy::FLAG_RUNTIMEPARTIAL |
50 11
            LightnCandy::FLAG_HANDLEBARSLAMBDA |
51 11
            LightnCandy::FLAG_EXTHELPER |
52 11
            LightnCandy::FLAG_ERROR_EXCEPTION) &
53 11
            ~LightnCandy::FLAG_STANDALONEPHP
54
        ;
55 11
        $this->options = array_merge([
56 11
            'auto_reload' => null,
57
            'debug' => true,
58 11
            'flags' => $flags,
59 11
            'helpers' => $helper->getHelperMethods(),
60 11
            'partialresolver' => function ($cx, $name) use ($loader, &$partials) {
61 2
                $extension = false;
62 2
                if ($loader->exists($name . '.handlebars')) {
63
                    $extension = '.handlebars';
64 2
                } else if ($loader->exists($name . '.hbs')) {
65 2
                    $extension = '.hbs';
66
                }
67 2
                if ($extension === false) {
68
                    return null;
69
                }
70 2
                $partials[] = new FileResource($loader->getCacheKey($name . $extension));
71 2
                return $loader->getSource($name . $extension);
72 11
            },
73
        ], $options);
74 11
        $this->debug = (bool) $this->options['debug'];
75 11
        $this->autoReload = null === $this->options['auto_reload'] ? $this->debug : (bool) $this->options['auto_reload'];
76 11
        $this->cache = $cache;
77 11
        $this->profiler = $profiler;
78 11
    }
79
80 4
    public function compile($name)
81
    {
82 4
        $source = $this->getLoader()->getSource($name);
83 4
        $cacheKey = $this->getCacheFilename($name);
84
85 4
        $phpStr = '';
86
        try {
87 4
            $this->partials->exchangeArray([new FileResource($this->getLoader()->getCacheKey($name))]);
88 4
            $phpStr = LightnCandy::compile($source, $this->options);
89
        } catch (\Exception $e) {
90
            throw new LoaderException($e->getMessage());
91
        }
92 4
        $this->cache->write($cacheKey, '<?php // ' . $name . PHP_EOL . $phpStr, $this->partials->getArrayCopy());
93
94 4
        return $phpStr;
95
    }
96
97 2
    public function render($name, array $context = [])
98
    {
99 2
        $renderer = $this->loadTemplate($name);
100
101 2
        $templateProfile = new \Twig_Profiler_Profile($name, \Twig_Profiler_Profile::TEMPLATE, $name);
102 2
        $this->profiler->enter($templateProfile);
103 2
        $html = $renderer($context, ['helpers' => $this->helper->getHelpers()]);
104 2
        $this->profiler->leave($templateProfile);
105
106 2
        return $html;
107
    }
108
109 11
    public function getCacheFilename($name)
110
    {
111 11
        $key = $this->cache->generateKey($name);
112
113 11
        return !$key ? false : $key;
114
    }
115
116 4
    public function getLoader()
117
    {
118 4
        return $this->loader;
119
    }
120
121
    /**
122
     * @param $templateName
123
     * @return callable
124
     */
125 7
    public function loadTemplate($templateName)
126
    {
127 7
        $name = (string)$templateName;
128 7
        $cacheKey = $this->getCacheFilename($name);
129 7
        if (!$this->isAutoReload() && file_exists($cacheKey)) {
130 1
            return $this->cache->load($cacheKey);
131 6
        } else if ($this->isAutoReload() && $this->cache->isFresh($cacheKey)) {
132 2
            return $this->cache->load($cacheKey);
133
        }
134 4
        $this->compile($name);
135
136 4
        return $this->cache->load($cacheKey);
137
    }
138
139
    /**
140
     * Checks if the auto_reload option is enabled.
141
     *
142
     * @return bool true if auto_reload is enabled, false otherwise
143
     */
144 7
    public function isAutoReload()
145
    {
146 7
        return $this->autoReload;
147
    }
148
}
149