Completed
Push — master ( 72dcf8...3bfcae )
by Iurii
01:08
created

Twig.php (2 issues)

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 gplcart\core\Module;
13
14
/**
15
 * Main class for Twig module
16
 */
17
class Twig extends Module
18
{
19
20
    /**
21
     * An array of TWIG instances keyed by file directory
22
     * @var array
23
     */
24
    protected $twig = array();
25
26
    /**
27
     * Constructor
28
     */
29
    public function __construct()
30
    {
31
        parent::__construct();
32
    }
33
34
    /**
35
     * Implements hook "library.list"
36
     * @param array $libraries
37
     */
38
    public function hookLibraryList(array &$libraries)
39
    {
40
        $libraries['twig'] = array(
41
            'name' => 'Twig',
42
            'description' => 'Twig is a template engine for PHP',
43
            'url' => 'https://github.com/twigphp/Twig',
44
            'download' => 'https://github.com/twigphp/Twig/archive/v1.33.0.zip',
45
            'type' => 'php',
46
            'module' => 'twig',
47
            'version_source' => array(
48
                'lines' => 100,
49
                'pattern' => '/.*VERSION.*(\\d+\\.+\\d+\\.+\\d+)/',
50
                'file' => 'vendor/twig/twig/lib/Twig/Environment.php'
51
            ),
52
            'files' => array(
53
                'vendor/autoload.php'
54
            )
55
        );
56
    }
57
58
    /**
59
     * Implements hook "route.list"
60
     * @param array $routes
61
     */
62
    public function hookRouteList(array &$routes)
63
    {
64
        $routes['admin/module/settings/twig'] = array(
65
            'access' => 'module_edit',
66
            'handlers' => array(
67
                'controller' => array('gplcart\\modules\\twig\\controllers\\Settings', 'editSettings')
68
            )
69
        );
70
    }
71
72
    /**
73
     * Implements hook "template.render"
74
     * @param array $templates
75
     * @param array $data
76
     * @param null|string $rendered
77
     * @param \gplcart\core\Controller $object
78
     */
79
    public function hookTemplateRender($templates, $data, &$rendered, $object)
80
    {
81
        list($original, $overridden) = $templates;
82
83
        if (is_file("$overridden.twig")) {
84
            $rendered = $this->render("$overridden.twig", $data, $object);
85
        } else if (is_file("$original.twig")) {
86
            $rendered = $this->render("$original.twig", $data, $object);
87
        }
88
    }
89
90
    /**
91
     * Returns a TWIG instance for the given file directory
92
     * @param string $path
93
     * @param \gplcart\core\Controller $object
94
     * @return \Twig_Environment
95
     */
96
    public function getTwigInstance($path, $object)
97
    {
98
        $options = array();
99
100
        if (empty($this->twig)) {
101
            $this->getLibrary()->load('twig');
102
            $options = $this->config->module('twig');
103
        }
104
105
        if (isset($this->twig[$path])) {
106
            return $this->twig[$path];
107
        }
108
109
        if (!empty($options['cache'])) {
110
            $options['cache'] = __DIR__ . '/cache';
111
        }
112
113
        $twig = new \Twig_Environment(new \Twig_Loader_Filesystem($path), $options);
114
115
        if (!empty($options['debug'])) {
116
            $twig->addExtension(new \Twig_Extension_Debug());
117
        }
118
119
        foreach ($this->getDefaultFunctions($object) as $function) {
120
            $twig->addFunction($function);
121
        }
122
123
        return $this->twig[$path] = $twig;
124
    }
125
126
    /**
127
     * Renders a .twig template
128
     * @param string $template
129
     * @param array $data
130
     * @param \gplcart\core\Controller $object
131
     * @return string
132
     */
133
    public function render($template, $data, $object)
134
    {
135
        $parts = explode('/', $template);
136
        $file = array_pop($parts);
137
        $twig = $this->getTwigInstance(implode('/', $parts), $object);
138
139
        $controller_data = $object->getData();
140
        return $twig->loadTemplate($file)->render(array_merge($controller_data, $data));
141
    }
142
143
    /**
144
     * Validate a TWIG template syntax
145
     * @param string $file
146
     * @param \gplcart\core\Controller $controller
147
     * @return boolean|string
148
     */
149
    public function validate($file, $controller)
150
    {
151
        $info = pathinfo($file);
152
        $twig = $this->getTwigInstance($info['dirname'], $controller);
153
154
        try {
155
            $content = file_get_contents($file);
156
            $twig->parse($twig->tokenize(new \Twig_Source($content, $info['basename'])));
157
            return true;
158
        } catch (\Twig_Error_Syntax $e) {
0 ignored issues
show
The class Twig_Error_Syntax does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
159
            return $e->getMessage();
160
        }
161
    }
162
163
    /**
164
     * Adds custom functions and returns an array of Twig_SimpleFunction objects
165
     * @param \gplcart\core\Controller $controller
166
     * @return array
167
     */
168
    protected function getDefaultFunctions($controller)
169
    {
170
        if (!$controller instanceof \gplcart\core\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...
171
            throw new \InvalidArgumentException('Argument must be instance of \gplcart\core\Controller');
172
        }
173
174
        $functions = array();
175
176
        $functions[] = new \Twig_SimpleFunction('error', function ($key = null, $has_error = null, $no_error = '') use ($controller) {
177
            return $controller->error($key, $has_error, $no_error);
178
        }, array('is_safe' => array('all')));
179
180
        $functions[] = new \Twig_SimpleFunction('text', function ($text, $arguments = array()) use ($controller) {
181
            return $controller->text($text, $arguments);
182
        }, array('is_safe' => array('all')));
183
184
        $functions[] = new \Twig_SimpleFunction('access', function ($permission) use ($controller) {
185
            return $controller->access($permission);
186
        });
187
188
        $functions[] = new \Twig_SimpleFunction('url', function ($path = '', array $query = array(), $absolute = false) use ($controller) {
189
            return $controller->url($path, $query, $absolute);
190
        });
191
192
        $functions[] = new \Twig_SimpleFunction('date', function ($timestamp = null, $full = true, $unix_format = '') use ($controller) {
193
            return $controller->date($timestamp, $full, $unix_format);
194
        });
195
196
        $functions[] = new \Twig_SimpleFunction('attributes', function ($attributes) use ($controller) {
197
            return $controller->attributes($attributes);
198
        }, array('is_safe' => array('all')));
199
200
        $functions[] = new \Twig_SimpleFunction('config', function ($key = null, $default = null) use ($controller) {
201
            return $controller->config($key, $default);
202
        });
203
204
        $functions[] = new \Twig_SimpleFunction('configTheme', function ($key = null, $default = null) use ($controller) {
205
            return $controller->configTheme($key, $default);
206
        });
207
208
        $functions[] = new \Twig_SimpleFunction('summary', function ($text, $xss = false, $filter = null) use ($controller) {
209
            return $controller->summary($text, $xss, $filter);
210
        }, array('is_safe' => array('all')));
211
212
        $functions[] = new \Twig_SimpleFunction('filter', function ($text, $filter = null) use ($controller) {
213
            return $controller->filter($text, $filter);
214
        }, array('is_safe' => array('all')));
215
216
        $functions[] = new \Twig_SimpleFunction('truncate', function ($string, $length = 100, $trimmarker = '...') use ($controller) {
217
            return $controller->truncate($string, $length, $trimmarker);
218
        });
219
220
        $functions[] = new \Twig_SimpleFunction('path', function ($path = null) use ($controller) {
221
            return $controller->path($path);
222
        });
223
224
        return $functions;
225
    }
226
227
    /**
228
     * Implements hook "module.enable.after"
229
     */
230
    public function hookModuleEnableAfter()
231
    {
232
        $this->getLibrary()->clearCache();
233
    }
234
235
    /**
236
     * Implements hook "module.disable.after"
237
     */
238
    public function hookModuleDisableAfter()
239
    {
240
        $this->getLibrary()->clearCache();
241
    }
242
243
    /**
244
     * Implements hook "module.install.after"
245
     */
246
    public function hookModuleInstallAfter()
247
    {
248
        $this->getLibrary()->clearCache();
249
    }
250
251
    /**
252
     * Implements hook "module.uninstall.after"
253
     */
254
    public function hookModuleUninstallAfter()
255
    {
256
        $this->getLibrary()->clearCache();
257
    }
258
259
}
260