Completed
Push — master ( 2a5c5f...c6091a )
by Iurii
01:06
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
14
/**
15
 * Main class for Twig module
16
 */
17
class Twig extends Module
18
{
19
20
    /**
21
     * An array of TWIG instances keyed by a 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
        try {
136
            $parts = explode('/', $template);
137
            $file = array_pop($parts);
138
            $twig = $this->getTwigInstance(implode('/', $parts), $object);
139
            $controller_data = $object->getData();
140
            return $twig->loadTemplate($file)->render(array_merge($controller_data, $data));
141
        } catch (\Exception $ex) {
142
            return $ex->getMessage();
143
        }
144
    }
145
146
    /**
147
     * Validate a TWIG template syntax
148
     * @param string $file
149
     * @param \gplcart\core\Controller $controller
150
     * @return boolean|string
151
     */
152
    public function validate($file, $controller)
153
    {
154
        try {
155
            $info = pathinfo($file);
156
            $twig = $this->getTwigInstance($info['dirname'], $controller);
157
            $content = file_get_contents($file);
158
            $twig->parse($twig->tokenize(new \Twig_Source($content, $info['basename'])));
159
            return true;
160
        } catch (\Exception $ex) {
161
            return $ex->getMessage();
162
        }
163
    }
164
165
    /**
166
     * Adds custom functions and returns an array of Twig_SimpleFunction objects
167
     * @param \gplcart\core\Controller $controller
168
     * @return array
169
     */
170
    protected function getDefaultFunctions($controller)
171
    {
172
        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...
173
            throw new \InvalidArgumentException('Argument must be instance of \gplcart\core\Controller');
174
        }
175
176
        $functions = array();
177
178
        $functions[] = new \Twig_SimpleFunction('error', function ($key = null, $has_error = null, $no_error = '') use ($controller) {
179
            return $controller->error($key, $has_error, $no_error);
180
        }, array('is_safe' => array('all')));
181
182
        $functions[] = new \Twig_SimpleFunction('text', function ($text, $arguments = array()) use ($controller) {
183
            return $controller->text($text, $arguments);
184
        }, array('is_safe' => array('all')));
185
186
        $functions[] = new \Twig_SimpleFunction('access', function ($permission) use ($controller) {
187
            return $controller->access($permission);
188
        });
189
190
        $functions[] = new \Twig_SimpleFunction('url', function ($path = '', array $query = array(), $absolute = false) use ($controller) {
191
            return $controller->url($path, $query, $absolute);
192
        });
193
194
        $functions[] = new \Twig_SimpleFunction('date', function ($timestamp = null, $full = true, $unix_format = '') use ($controller) {
195
            return $controller->date($timestamp, $full, $unix_format);
196
        });
197
198
        $functions[] = new \Twig_SimpleFunction('attributes', function ($attributes) use ($controller) {
199
            return $controller->attributes($attributes);
200
        }, array('is_safe' => array('all')));
201
202
        $functions[] = new \Twig_SimpleFunction('config', function ($key = null, $default = null) use ($controller) {
203
            return $controller->config($key, $default);
204
        });
205
206
        $functions[] = new \Twig_SimpleFunction('configTheme', function ($key = null, $default = null) use ($controller) {
207
            return $controller->configTheme($key, $default);
208
        });
209
210
        $functions[] = new \Twig_SimpleFunction('summary', function ($text, $xss = false, $filter = null) use ($controller) {
211
            return $controller->summary($text, $xss, $filter);
212
        }, array('is_safe' => array('all')));
213
214
        $functions[] = new \Twig_SimpleFunction('filter', function ($text, $filter = null) use ($controller) {
215
            return $controller->filter($text, $filter);
216
        }, array('is_safe' => array('all')));
217
218
        $functions[] = new \Twig_SimpleFunction('truncate', function ($string, $length = 100, $trimmarker = '...') use ($controller) {
219
            return $controller->truncate($string, $length, $trimmarker);
220
        });
221
222
        $functions[] = new \Twig_SimpleFunction('path', function ($path = null) use ($controller) {
223
            return $controller->path($path);
224
        });
225
226
        return $functions;
227
    }
228
229
    /**
230
     * Implements hook "module.enable.after"
231
     */
232
    public function hookModuleEnableAfter()
233
    {
234
        $this->getLibrary()->clearCache();
235
    }
236
237
    /**
238
     * Implements hook "module.disable.after"
239
     */
240
    public function hookModuleDisableAfter()
241
    {
242
        $this->getLibrary()->clearCache();
243
    }
244
245
    /**
246
     * Implements hook "module.install.after"
247
     */
248
    public function hookModuleInstallAfter()
249
    {
250
        $this->getLibrary()->clearCache();
251
    }
252
253
    /**
254
     * Implements hook "module.uninstall.after"
255
     */
256
    public function hookModuleUninstallAfter()
257
    {
258
        $this->getLibrary()->clearCache();
259
    }
260
261
}
262