Completed
Push — master ( 60f3a3...90a919 )
by Iurii
01:19
created

Main.php (1 issue)

Labels
Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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 Exception;
13
use gplcart\core\Controller;
14
use gplcart\core\Library;
15
use gplcart\core\Module;
16
use InvalidArgumentException;
17
use Twig_Environment;
18
use Twig_Extension_Debug;
19
use Twig_Loader_Filesystem;
20
use Twig_SimpleFunction;
21
use Twig_Source;
22
23
/**
24
 * Main class for Twig module
25
 */
26
class Main
27
{
28
29
    /**
30
     * An array of TWIG instances keyed by a file directory
31
     * @var array
32
     */
33
    protected $twig = array();
34
35
    /**
36
     * Module class instance
37
     * @var \gplcart\core\Module $module
38
     */
39
    protected $module;
40
41
    /**
42
     * Library class instance
43
     * @var \gplcart\core\Library $library
44
     */
45
    protected $library;
46
47
    /**
48
     * @param Module $module
49
     * @param Library $library
50
     */
51
    public function __construct(Module $module, Library $library)
52
    {
53
        $this->module = $module;
54
        $this->library = $library;
55
    }
56
57
    /**
58
     * Implements hook "library.list"
59
     * @param array $libraries
60
     */
61
    public function hookLibraryList(array &$libraries)
62
    {
63
        $libraries['twig'] = array(
64
            'name' => 'Twig',
65
            'description' => 'Twig is a template engine for PHP',
66
            'url' => 'https://github.com/twigphp/Twig',
67
            'download' => 'https://github.com/twigphp/Twig/archive/v1.33.0.zip',
68
            'type' => 'php',
69
            'module' => 'twig',
70
            'version_source' => array(
71
                'lines' => 100,
72
                'pattern' => '/.*VERSION.*(\\d+\\.+\\d+\\.+\\d+)/',
73
                'file' => 'vendor/twig/twig/lib/Twig/Environment.php'
74
            ),
75
            'files' => array(
76
                'vendor/autoload.php'
77
            )
78
        );
79
    }
80
81
    /**
82
     * Implements hook "route.list"
83
     * @param array $routes
84
     */
85
    public function hookRouteList(array &$routes)
86
    {
87
        $routes['admin/module/settings/twig'] = array(
88
            'access' => 'module_edit',
89
            'handlers' => array(
90
                'controller' => array('gplcart\\modules\\twig\\controllers\\Settings', 'editSettings')
91
            )
92
        );
93
    }
94
95
    /**
96
     * Implements hook "template.render"
97
     * @param array $templates
98
     * @param array $data
99
     * @param null|string $rendered
100
     * @param \gplcart\core\Controller $controller
101
     */
102
    public function hookTemplateRender($templates, $data, &$rendered, $controller)
103
    {
104
        $this->setRenderedTemplate($templates, $data, $rendered, $controller);
105
    }
106
107
    /**
108
     * Implements hook "module.enable.after"
109
     */
110
    public function hookModuleEnableAfter()
111
    {
112
        $this->library->clearCache();
113
    }
114
115
    /**
116
     * Implements hook "module.disable.after"
117
     */
118
    public function hookModuleDisableAfter()
119
    {
120
        $this->library->clearCache();
121
    }
122
123
    /**
124
     * Implements hook "module.install.after"
125
     */
126
    public function hookModuleInstallAfter()
127
    {
128
        $this->library->clearCache();
129
    }
130
131
    /**
132
     * Implements hook "module.uninstall.after"
133
     */
134
    public function hookModuleUninstallAfter()
135
    {
136
        $this->library->clearCache();
137
    }
138
139
    /**
140
     * Returns a TWIG instance for the given file directory
141
     * @param string $path
142
     * @param Controller $controller
143
     * @return Twig_Environment
144
     * @throws InvalidArgumentException
145
     */
146
    public function getTwigInstance($path, $controller)
147
    {
148
        if (!$controller instanceof Controller) {
0 ignored issues
show
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...
149
            throw new InvalidArgumentException('Second argument must be instance of \gplcart\core\Controller');
150
        }
151
152
        $options = array();
153
154
        if (empty($this->twig)) {
155
            $this->library->load('twig');
156
            $options = $this->module->getSettings('twig');
157
        }
158
159
        if (isset($this->twig[$path])) {
160
            return $this->twig[$path];
161
        }
162
163
        if (!empty($options['cache'])) {
164
            $options['cache'] = __DIR__ . '/cache';
165
        }
166
167
        $twig = new Twig_Environment(new Twig_Loader_Filesystem($path), $options);
168
169
        if (!empty($options['debug'])) {
170
            $twig->addExtension(new Twig_Extension_Debug());
171
        }
172
173
        foreach ($this->getDefaultFunctions($controller) as $function) {
174
            $twig->addFunction($function);
175
        }
176
177
        return $this->twig[$path] = $twig;
178
    }
179
180
    /**
181
     * Renders a .twig template
182
     * @param string $template
183
     * @param array $data
184
     * @param Controller $controller
185
     * @return string
186
     */
187
    public function render($template, $data, Controller $controller)
188
    {
189
        try {
190
            $parts = explode('/', $template);
191
            $file = array_pop($parts);
192
            $twig = $this->getTwigInstance(implode('/', $parts), $controller);
193
            $controller_data = $controller->getData();
194
            return $twig->loadTemplate($file)->render(array_merge($controller_data, $data));
195
        } catch (Exception $ex) {
196
            return $ex->getMessage();
197
        }
198
    }
199
200
    /**
201
     * Validate a TWIG template syntax
202
     * @param string $file
203
     * @param Controller $controller
204
     * @return boolean|string
205
     */
206
    public function validate($file, Controller $controller)
207
    {
208
        try {
209
            $pathinfo = pathinfo($file);
210
            $twig = $this->getTwigInstance($pathinfo['dirname'], $controller);
211
            $content = file_get_contents($file);
212
            $twig->parse($twig->tokenize(new Twig_Source($content, $pathinfo['basename'])));
213
            return true;
214
        } catch (Exception $ex) {
215
            return $ex->getMessage();
216
        }
217
    }
218
219
    /**
220
     * Sets rendered .twig template
221
     * @param array $templates
222
     * @param array $data
223
     * @param null|string $rendered
224
     * @param Controller $controller
225
     */
226
    protected function setRenderedTemplate($templates, $data, &$rendered, Controller $controller)
227
    {
228
        list($original, $overridden) = $templates;
229
230
        if (is_file("$overridden.twig")) {
231
            $rendered = $this->render("$overridden.twig", $data, $controller);
232
        } else if (is_file("$original.twig")) {
233
            $rendered = $this->render("$original.twig", $data, $controller);
234
        }
235
    }
236
237
    /**
238
     * Adds custom functions and returns an array of Twig_SimpleFunction objects
239
     * @param Controller $controller
240
     * @return array
241
     */
242
    protected function getDefaultFunctions(Controller $controller)
243
    {
244
        $functions = array();
245
246
        $functions[] = new Twig_SimpleFunction('error', function ($key = null, $has_error = null, $no_error = '') use ($controller) {
247
            return $controller->error($key, $has_error, $no_error);
248
        }, array('is_safe' => array('all')));
249
250
        $functions[] = new Twig_SimpleFunction('text', function ($text, $arguments = array()) use ($controller) {
251
            return $controller->text($text, $arguments);
252
        }, array('is_safe' => array('all')));
253
254
        $functions[] = new Twig_SimpleFunction('access', function ($permission) use ($controller) {
255
            return $controller->access($permission);
256
        });
257
258
        $functions[] = new Twig_SimpleFunction('url', function ($path = '', array $query = array(), $absolute = false) use ($controller) {
259
            return $controller->url($path, $query, $absolute);
260
        });
261
262
        $functions[] = new Twig_SimpleFunction('date', function ($timestamp = null, $full = true) use ($controller) {
263
            return $controller->date($timestamp, $full);
264
        });
265
266
        $functions[] = new Twig_SimpleFunction('attributes', function ($attributes) use ($controller) {
267
            return $controller->attributes($attributes);
268
        }, array('is_safe' => array('all')));
269
270
        $functions[] = new Twig_SimpleFunction('config', function ($key = null, $default = null) use ($controller) {
271
            return $controller->config($key, $default);
272
        });
273
274
        $functions[] = new Twig_SimpleFunction('configTheme', function ($key = null, $default = null) use ($controller) {
275
            return $controller->configTheme($key, $default);
276
        });
277
278
        $functions[] = new Twig_SimpleFunction('teaser', function ($text, $xss = false, $filter = null) use ($controller) {
279
            return $controller->teaser($text, $xss, $filter);
280
        }, array('is_safe' => array('all')));
281
282
        $functions[] = new Twig_SimpleFunction('filter', function ($text, $filter = null) use ($controller) {
283
            return $controller->filter($text, $filter);
284
        }, array('is_safe' => array('all')));
285
286
        $functions[] = new Twig_SimpleFunction('truncate', function ($string, $length = 100, $trimmarker = '...') use ($controller) {
287
            return $controller->truncate($string, $length, $trimmarker);
288
        });
289
290
        $functions[] = new Twig_SimpleFunction('path', function ($path = null) use ($controller) {
291
            return $controller->path($path);
292
        });
293
294
        return $functions;
295
    }
296
297
}
298