Completed
Push — master ( 03586b...9af9ed )
by Iurii
01:16
created

Twig::validate()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 11
nc 4
nop 2
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
     */
95
    public function getTwigInstance($path, $object)
96
    {
97
        $options = array();
98
99
        if (empty($this->twig)) {
100
            $this->getLibrary()->load('twig');
101
            $options = $this->config->module('twig');
102
        }
103
104
        if (isset($this->twig[$path])) {
105
            return $this->twig[$path];
106
        }
107
108
        if (!empty($options['cache'])) {
109
            $options['cache'] = __DIR__ . '/cache';
110
        }
111
112
        $twig = new \Twig_Environment(new \Twig_Loader_Filesystem($path), $options);
113
114
        if (!empty($options['debug'])) {
115
            $twig->addExtension(new \Twig_Extension_Debug());
116
        }
117
118
        foreach ($this->getDefaultFunctions($object) as $function) {
119
            $twig->addFunction($function);
120
        }
121
122
        return $this->twig[$path] = $twig;
123
    }
124
125
    /**
126
     * Renders a .twig template
127
     * @param string $template
128
     * @param array $data
129
     * @param \gplcart\core\Controller $object
130
     * @return string
131
     */
132
    public function render($template, $data, $object)
133
    {
134
        $parts = explode('/', $template);
135
        $file = array_pop($parts);
136
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
        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...
152
            throw new \InvalidArgumentException('Second argument must be instance of \gplcart\core\Controller');
153
        }
154
155
        $info = pathinfo($file);
156
        $twig = $this->getTwigInstance($info['dirname'], $controller);
157
158
        try {
159
            $content = file_get_contents($file);
160
            $twig->parse($twig->tokenize(new \Twig_Source($content, $info['basename'])));
161
            return true;
162
        } catch (\Twig_Error_Syntax $e) {
0 ignored issues
show
Bug introduced by
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...
163
            return $e->getMessage();
164
        }
165
    }
166
167
    /**
168
     * Adds custom functions and returns an array of Twig_SimpleFunction objects
169
     * @param \gplcart\core\Controller $controller
170
     * @return array
171
     */
172
    protected function getDefaultFunctions($controller)
173
    {
174
        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...
175
            throw new \InvalidArgumentException('Argument must be instance of \gplcart\core\Controller');
176
        }
177
178
        $functions = array();
179
180
        $functions[] = new \Twig_SimpleFunction('error', function ($key = null, $has_error = null, $no_error = '') use ($controller) {
181
            return $controller->error($key, $has_error, $no_error);
182
        }, array('is_safe' => array('all')));
183
184
        $functions[] = new \Twig_SimpleFunction('text', function ($text, $arguments = array()) use ($controller) {
185
            return $controller->text($text, $arguments);
186
        }, array('is_safe' => array('all')));
187
188
        $functions[] = new \Twig_SimpleFunction('access', function ($permission) use ($controller) {
189
            return $controller->access($permission);
190
        });
191
192
        $functions[] = new \Twig_SimpleFunction('url', function ($path = '', array $query = array(), $absolute = false) use ($controller) {
193
            return $controller->url($path, $query, $absolute);
194
        });
195
196
        $functions[] = new \Twig_SimpleFunction('date', function ($timestamp = null, $full = true, $unix_format = '') use ($controller) {
197
            return $controller->date($timestamp, $full, $unix_format);
198
        });
199
200
        $functions[] = new \Twig_SimpleFunction('attributes', function ($attributes) use ($controller) {
201
            return $controller->attributes($attributes);
202
        }, array('is_safe' => array('all')));
203
204
        $functions[] = new \Twig_SimpleFunction('config', function ($key = null, $default = null) use ($controller) {
205
            return $controller->config($key, $default);
206
        });
207
208
        $functions[] = new \Twig_SimpleFunction('configTheme', function ($key = null, $default = null) use ($controller) {
209
            return $controller->configTheme($key, $default);
210
        });
211
212
        $functions[] = new \Twig_SimpleFunction('summary', function ($text, $xss = false, $filter = null) use ($controller) {
213
            return $controller->summary($text, $xss, $filter);
214
        }, array('is_safe' => array('all')));
215
216
        $functions[] = new \Twig_SimpleFunction('filter', function ($text, $filter = null) use ($controller) {
217
            return $controller->filter($text, $filter);
218
        }, array('is_safe' => array('all')));
219
220
        $functions[] = new \Twig_SimpleFunction('truncate', function ($string, $length = 100, $trimmarker = '...') use ($controller) {
221
            return $controller->truncate($string, $length, $trimmarker);
222
        });
223
224
        $functions[] = new \Twig_SimpleFunction('path', function ($path = null) use ($controller) {
225
            return $controller->path($path);
226
        });
227
228
        return $functions;
229
    }
230
231
    /**
232
     * Implements hook "module.enable.after"
233
     */
234
    public function hookModuleEnableAfter()
235
    {
236
        $this->getLibrary()->clearCache();
237
    }
238
239
    /**
240
     * Implements hook "module.disable.after"
241
     */
242
    public function hookModuleDisableAfter()
243
    {
244
        $this->getLibrary()->clearCache();
245
    }
246
247
    /**
248
     * Implements hook "module.install.after"
249
     */
250
    public function hookModuleInstallAfter()
251
    {
252
        $this->getLibrary()->clearCache();
253
    }
254
255
    /**
256
     * Implements hook "module.uninstall.after"
257
     */
258
    public function hookModuleUninstallAfter()
259
    {
260
        $this->getLibrary()->clearCache();
261
    }
262
263
}
264