Completed
Push — master ( 274727...367325 )
by Iurii
01:16
created

Twig::setRenderedTemplate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 4
1
<?php
2
3
/**
4
 * @package Twig
5
 * @author Iurii Makukh <[email protected]>
6
 * @copyright Copyright (c) 2015, Iurii Makukh
7
 * @license https://www.gnu.org/licenses/gpl.html GNU/GPLv3
8
 */
9
10
namespace gplcart\modules\twig;
11
12
use gplcart\core\Module,
13
    gplcart\core\Config;
14
15
/**
16
 * Main class for Twig module
17
 */
18
class Twig extends Module
19
{
20
21
    /**
22
     * An array of TWIG instances keyed by a file directory
23
     * @var array
24
     */
25
    protected $twig = array();
26
27
    /**
28
     * @param Config $config
29
     */
30
    public function __construct(Config $config)
31
    {
32
        parent::__construct($config);
33
    }
34
35
    /* ------------------------ Hooks ------------------------ */
36
37
    /**
38
     * Implements hook "library.list"
39
     * @param array $libraries
40
     */
41
    public function hookLibraryList(array &$libraries)
42
    {
43
        $libraries['twig'] = array(
44
            'name' => 'Twig',
45
            'description' => 'Twig is a template engine for PHP',
46
            'url' => 'https://github.com/twigphp/Twig',
47
            'download' => 'https://github.com/twigphp/Twig/archive/v1.33.0.zip',
48
            'type' => 'php',
49
            'module' => 'twig',
50
            'version_source' => array(
51
                'lines' => 100,
52
                'pattern' => '/.*VERSION.*(\\d+\\.+\\d+\\.+\\d+)/',
53
                'file' => 'vendor/twig/twig/lib/Twig/Environment.php'
54
            ),
55
            'files' => array(
56
                'vendor/autoload.php'
57
            )
58
        );
59
    }
60
61
    /**
62
     * Implements hook "route.list"
63
     * @param array $routes
64
     */
65
    public function hookRouteList(array &$routes)
66
    {
67
        $routes['admin/module/settings/twig'] = array(
68
            'access' => 'module_edit',
69
            'handlers' => array(
70
                'controller' => array('gplcart\\modules\\twig\\controllers\\Settings', 'editSettings')
71
            )
72
        );
73
    }
74
75
    /**
76
     * Implements hook "template.render"
77
     * @param array $templates
78
     * @param array $data
79
     * @param null|string $rendered
80
     * @param \gplcart\core\Controller $controller
81
     */
82
    public function hookTemplateRender($templates, $data, &$rendered, $controller)
83
    {
84
        $this->setRenderedTemplate($templates, $data, $rendered, $controller);
85
    }
86
87
    /**
88
     * Implements hook "module.enable.after"
89
     */
90
    public function hookModuleEnableAfter()
91
    {
92
        $this->getLibrary()->clearCache();
93
    }
94
95
    /**
96
     * Implements hook "module.disable.after"
97
     */
98
    public function hookModuleDisableAfter()
99
    {
100
        $this->getLibrary()->clearCache();
101
    }
102
103
    /**
104
     * Implements hook "module.install.after"
105
     */
106
    public function hookModuleInstallAfter()
107
    {
108
        $this->getLibrary()->clearCache();
109
    }
110
111
    /**
112
     * Implements hook "module.uninstall.after"
113
     */
114
    public function hookModuleUninstallAfter()
115
    {
116
        $this->getLibrary()->clearCache();
117
    }
118
119
    /* ------------------------ API ------------------------ */
120
121
    /**
122
     * Returns a TWIG instance for the given file directory
123
     * @param string $path
124
     * @param \gplcart\core\Controller $controller
125
     * @return \Twig_Environment
126
     */
127
    public function getTwigInstance($path, $controller)
128
    {
129
        $options = array();
130
131
        if (empty($this->twig)) {
132
            $this->getLibrary()->load('twig');
133
            $options = $this->config->getFromModule('twig');
134
        }
135
136
        if (isset($this->twig[$path])) {
137
            return $this->twig[$path];
138
        }
139
140
        if (!empty($options['cache'])) {
141
            $options['cache'] = __DIR__ . '/cache';
142
        }
143
144
        $twig = new \Twig_Environment(new \Twig_Loader_Filesystem($path), $options);
145
146
        if (!empty($options['debug'])) {
147
            $twig->addExtension(new \Twig_Extension_Debug());
148
        }
149
150
        foreach ($this->getDefaultFunctions($controller) as $function) {
151
            $twig->addFunction($function);
152
        }
153
154
        return $this->twig[$path] = $twig;
155
    }
156
157
    /**
158
     * Renders a .twig template
159
     * @param string $template
160
     * @param array $data
161
     * @param \gplcart\core\Controller $object
162
     * @return string
163
     */
164
    public function render($template, $data, $object)
165
    {
166
        try {
167
            $parts = explode('/', $template);
168
            $file = array_pop($parts);
169
            $twig = $this->getTwigInstance(implode('/', $parts), $object);
170
            $controller_data = $object->getData();
171
            return $twig->loadTemplate($file)->render(array_merge($controller_data, $data));
172
        } catch (\Exception $ex) {
173
            return $ex->getMessage();
174
        }
175
    }
176
177
    /**
178
     * Validate a TWIG template syntax
179
     * @param string $file
180
     * @param \gplcart\core\Controller $controller
181
     * @return boolean|string
182
     */
183
    public function validate($file, $controller)
184
    {
185
        try {
186
            $info = pathinfo($file);
187
            $twig = $this->getTwigInstance($info['dirname'], $controller);
188
            $content = file_get_contents($file);
189
            $twig->parse($twig->tokenize(new \Twig_Source($content, $info['basename'])));
190
            return true;
191
        } catch (\Exception $ex) {
192
            return $ex->getMessage();
193
        }
194
    }
195
196
    /* ------------------------ Helpers ------------------------ */
197
198
    /**
199
     * Sets rendered .twig template
200
     * @param array $templates
201
     * @param array $data
202
     * @param null|string $rendered
203
     * @param \gplcart\core\Controller $controller
204
     */
205
    protected function setRenderedTemplate($templates, $data, &$rendered, $controller)
206
    {
207
        list($original, $overridden) = $templates;
208
209
        if (is_file("$overridden.twig")) {
210
            $rendered = $this->render("$overridden.twig", $data, $controller);
211
        } else if (is_file("$original.twig")) {
212
            $rendered = $this->render("$original.twig", $data, $controller);
213
        }
214
    }
215
216
    /**
217
     * Adds custom functions and returns an array of Twig_SimpleFunction objects
218
     * @param \gplcart\core\Controller $controller
219
     * @return array
220
     */
221
    protected function getDefaultFunctions($controller)
222
    {
223
        if (!$controller instanceof \gplcart\core\Controller) {
0 ignored issues
show
Bug introduced by
The class gplcart\core\Controller does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
224
            throw new \InvalidArgumentException('Argument must be instance of \gplcart\core\Controller');
225
        }
226
227
        $functions = array();
228
229
        $functions[] = new \Twig_SimpleFunction('error', function ($key = null, $has_error = null, $no_error = '') use ($controller) {
230
            return $controller->error($key, $has_error, $no_error);
231
        }, array('is_safe' => array('all')));
232
233
        $functions[] = new \Twig_SimpleFunction('text', function ($text, $arguments = array()) use ($controller) {
234
            return $controller->text($text, $arguments);
235
        }, array('is_safe' => array('all')));
236
237
        $functions[] = new \Twig_SimpleFunction('access', function ($permission) use ($controller) {
238
            return $controller->access($permission);
239
        });
240
241
        $functions[] = new \Twig_SimpleFunction('url', function ($path = '', array $query = array(), $absolute = false) use ($controller) {
242
            return $controller->url($path, $query, $absolute);
243
        });
244
245
        $functions[] = new \Twig_SimpleFunction('date', function ($timestamp = null, $full = true, $unix_format = '') use ($controller) {
246
            return $controller->date($timestamp, $full, $unix_format);
247
        });
248
249
        $functions[] = new \Twig_SimpleFunction('attributes', function ($attributes) use ($controller) {
250
            return $controller->attributes($attributes);
251
        }, array('is_safe' => array('all')));
252
253
        $functions[] = new \Twig_SimpleFunction('config', function ($key = null, $default = null) use ($controller) {
254
            return $controller->config($key, $default);
255
        });
256
257
        $functions[] = new \Twig_SimpleFunction('configTheme', function ($key = null, $default = null) use ($controller) {
258
            return $controller->configTheme($key, $default);
259
        });
260
261
        $functions[] = new \Twig_SimpleFunction('teaser', function ($text, $xss = false, $filter = null) use ($controller) {
262
            return $controller->teaser($text, $xss, $filter);
263
        }, array('is_safe' => array('all')));
264
265
        $functions[] = new \Twig_SimpleFunction('filter', function ($text, $filter = null) use ($controller) {
266
            return $controller->filter($text, $filter);
267
        }, array('is_safe' => array('all')));
268
269
        $functions[] = new \Twig_SimpleFunction('truncate', function ($string, $length = 100, $trimmarker = '...') use ($controller) {
270
            return $controller->truncate($string, $length, $trimmarker);
271
        });
272
273
        $functions[] = new \Twig_SimpleFunction('path', function ($path = null) use ($controller) {
274
            return $controller->path($path);
275
        });
276
277
        return $functions;
278
    }
279
280
}
281