Main::hookRouteList()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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