Completed
Push — master ( e49e27...274727 )
by Iurii
01:03
created

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