Completed
Push — master ( fbef63...72dcf8 )
by Iurii
01:17
created

Twig::getDefaultFunctions()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 58
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 58
rs 9.639
c 0
b 0
f 0
cc 2
eloc 34
nc 2
nop 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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