Test Failed
Push — master ( ca6537...6c2c4e )
by Vojta
05:48
created

Plugin.php (1 issue)

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 namespace VojtaSvoboda\TwigExtensions;
2
3
use App;
4
use Backend;
5
use Carbon\Carbon;
6
use Snilius\Twig\SortByFieldExtension;
7
use System\Classes\PluginBase;
8
use Twig_Extension_StringLoader;
9
use Twig_Extensions_Extension_Array;
10
use Twig_Extensions_Extension_Date;
11
use Twig_Extensions_Extension_Intl;
12
use Twig_Extensions_Extension_Text;
13
use VojtaSvoboda\TwigExtensions\Classes\TimeDiffTranslator;
14
15
/**
16
 * Twig Extensions Plugin.
17
 *
18
 * @see http://twig.sensiolabs.org/doc/extensions/index.html#extensions-install
19
 */
20
class Plugin extends PluginBase
21
{
22
    /**
23
     * @var boolean Determine if this plugin should have elevated privileges.
24
     */
25
    public $elevated = true;
26
27
    /**
28
     * Returns information about this plugin.
29
     *
30
     * @return array
31
     */
32
    public function pluginDetails()
33
    {
34
        return [
35
            'name'        => 'Twig Extensions',
36
            'description' => 'Add more Twig filters to your templates.',
37
            'author'      => 'Vojta Svoboda',
38
            'icon'        => 'icon-plus',
39
            'homepage'    => 'https://github.com/vojtasvoboda/oc-twigextensions-plugin',
40
        ];
41
    }
42
43 View Code Duplication
    public function boot()
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
44
    {
45
        $this->app->singleton('time_diff_translator', function ($app) {
46
            $loader = $app->make('translation.loader');
47
            $locale = $app->config->get('app.locale');
48
            $translator = $app->make(TimeDiffTranslator::class, [$loader, $locale]);
49
            $translator->setFallback($app->config->get('app.fallback_locale'));
50
51
            return $translator;
52
        });
53
    }
54
55
    /**
56
     * Add Twig extensions.
57
     *
58
     * @see Text extensions http://twig.sensiolabs.org/doc/extensions/text.html
59 1
     * @see Intl extensions http://twig.sensiolabs.org/doc/extensions/intl.html
60
     * @see Array extension http://twig.sensiolabs.org/doc/extensions/array.html
61 1
     * @see Time extension http://twig.sensiolabs.org/doc/extensions/date.html
62 1
     *
63
     * @return array
64
     */
65 1
    public function registerMarkupTags()
66
    {
67
        $filters = [];
68 1
        $functions = [];
69
70
        // init Twig
71 1
        $twig = $this->app->make('twig.environment');
72
73
        // add String Loader functions
74 1
        $functions += $this->getStringLoaderFunctions($twig);
75
76
        // add Config function
77 1
        $functions += $this->getConfigFunction();
78
79
        // add Session function
80 1
        $functions += $this->getSessionFunction();
81
82
        // add Trans function
83 1
        $functions += $this->getTransFunction();
84
85
        // add var_dump function
86 1
        $functions += $this->getVarDumpFunction();
87 1
88 1
        // add Text extensions
89
        $filters += $this->getTextFilters($twig);
90
91 1
        // add Intl extensions if php5-intl installed
92
        if (class_exists('IntlDateFormatter')) {
93
            $filters += $this->getLocalizedFilters($twig);
94 1
        }
95
96
        // add Array extensions
97 1
        $filters += $this->getArrayFilters();
98
99
        // add Time extensions
100 1
        $filters += $this->getTimeFilters($twig);
101
102
        // add Sort by Field extensions
103 1
        $filters += $this->getSortByField();
104
105
        // add Mail filters
106 1
        $filters += $this->getMailFilters();
107 1
108 1
        // add PHP functions
109
        $filters += $this->getPhpFunctions();
110
111
        // add File Version filter
112
        $filters += $this->getFileRevision();
113
114
        return [
115
            'filters'   => $filters,
116
            'functions' => $functions,
117
        ];
118 1
    }
119
120 1
    /**
121 1
     * Returns String Loader functions.
122
     *
123
     * @param \Twig_Environment $twig
124
     *
125 1
     * @return array
126 1
     */
127
    private function getStringLoaderFunctions($twig)
128 1
    {
129
        $stringLoader = new Twig_Extension_StringLoader();
130
        $stringLoaderFunc = $stringLoader->getFunctions();
131
132
        return [
133
            'template_from_string' => function ($template) use ($twig, $stringLoaderFunc) {
134
                $callable = $stringLoaderFunc[0]->getCallable();
135
                return $callable($twig, $template);
136
            }
137
        ];
138 3
    }
139
140 1
    /**
141 1
     * Returns Text filters.
142
     *
143
     * @param \Twig_Environment $twig
144
     *
145 3
     * @return array
146 3
     */
147 1
    private function getTextFilters($twig)
148
    {
149 1
        $textExtension = new Twig_Extensions_Extension_Text();
150 1
        $textFilters = $textExtension->getFilters();
151
152 1
        return [
153
            'truncate' => function ($value, $length = 30, $preserve = false, $separator = '...') use ($twig, $textFilters) {
154
                $callable = $textFilters[0]->getCallable();
155
                return $callable($twig, $value, $length, $preserve, $separator);
156
            },
157
            'wordwrap' => function ($value, $length = 80, $separator = "\n", $preserve = false) use ($twig, $textFilters) {
158
                $callable = $textFilters[1]->getCallable();
159
                return $callable($twig, $value, $length, $separator, $preserve);
160
            }
161
        ];
162 1
    }
163
164 1
    /**
165 1
     * Returns Intl filters.
166
     *
167
     * @param \Twig_Environment $twig
168
     *
169
     * @return array
170
     */
171 1
    private function getLocalizedFilters($twig)
172
    {
173
        $intlExtension = new Twig_Extensions_Extension_Intl();
174
        $intlFilters = $intlExtension->getFilters();
175 1
176
        return [
177
            'localizeddate' => function ($date, $dateFormat = 'medium', $timeFormat = 'medium', $locale = null, $timezone = null, $format = null) use ($twig, $intlFilters) {
178
                $callable = $intlFilters[0]->getCallable();
179
                return $callable($twig, $date, $dateFormat, $timeFormat, $locale, $timezone, $format);
180 1
            },
181
            'localizednumber' => function ($number, $style = 'decimal', $type = 'default', $locale = null) use ($twig, $intlFilters) {
182
                $callable = $intlFilters[1]->getCallable();
183
                return $callable($number, $style, $type, $locale);
184
            },
185
            'localizedcurrency' => function ($number, $currency = null, $locale = null) use ($twig, $intlFilters) {
186
                $callable = $intlFilters[2]->getCallable();
187
                return $callable($number, $currency, $locale);
188 2
            }
189
        ];
190 1
    }
191 1
192
    /**
193
     * Returns Array filters.
194
     *
195 2
     * @return array
196 2
     */
197
    private function getArrayFilters()
198 1
    {
199
        $arrayExtension = new Twig_Extensions_Extension_Array();
200
        $arrayFilters = $arrayExtension->getFilters();
201
202
        return [
203
            'shuffle' => function ($array) use ($arrayFilters) {
204
                $callable = $arrayFilters[0]->getCallable();
205
                return $callable($array);
206
            }
207
        ];
208 1
    }
209
210 1
    /**
211 1
     * Returns Date filters.
212 1
     *
213
     * @param \Twig_Environment $twig
214
     *
215
     * @return array
216
     */
217
    private function getTimeFilters($twig)
218
    {
219 1
        $translator = $this->app->make('time_diff_translator');
220
        $timeExtension = new Twig_Extensions_Extension_Date($translator);
221
        $timeFilters = $timeExtension->getFilters();
222
223
        return [
224
            'time_diff' => function ($date, $now = null) use ($twig, $timeFilters) {
225
                $callable = $timeFilters[0]->getCallable();
226
                return $callable($twig, $date, $now);
227 1
            }
228
        ];
229
    }
230
231 1
    /**
232
     * Returns Sort by Field filters.
233 1
     *
234
     * @return array
235
     */
236
    private function getSortByField()
237
    {
238
        $extension = new SortByFieldExtension();
239
        $filters = $extension->getFilters();
240
241 1
        return [
242
            'sortbyfield' => function ($array, $sort_by = null, $direction = 'asc') use ($filters) {
243
                $callable = $filters[0]->getCallable();
244
                return $callable($array, $sort_by, $direction);
245 1
            }
246 1
        ];
247 1
    }
248
249 1
    /**
250 1
     * Returns mail filters.
251
     *
252 1
     * @return array
253 1
     */
254
    private function getMailFilters()
255 1
    {
256 1
        return [
257
            'mailto' => function ($string, $link = true, $protected = true, $text = null) {
258 1
                return $this->hideEmail($string, $link, $protected, $text);
259 1
            }
260
        ];
261 1
    }
262 1
263
    /**
264 1
     * Returns plain PHP functions.
265 1
     *
266
     * @return array
267 1
     */
268 1
    private function getPhpFunctions()
269
    {
270 1
        return [
271 1
            'strftime' => function ($time, $format = '%d.%m.%Y %H:%M:%S') {
272
                $timeObj = new Carbon($time);
273 1
                return strftime($format, $timeObj->getTimestamp());
274 1
            },
275
            'uppercase' => function ($string) {
276 1
                return mb_convert_case($string, MB_CASE_UPPER, "UTF-8");
277 1
            },
278
            'lowercase' => function ($string) {
279 1
                return mb_convert_case($string, MB_CASE_LOWER, "UTF-8");
280 1
            },
281
            'ucfirst' => function ($string) {
282 1
                return mb_convert_case($string, MB_CASE_TITLE, "UTF-8");
283 1
            },
284
            'lcfirst' => function ($string) {
285 1
                return lcfirst($string);
286 1
            },
287 1
            'ltrim' => function ($string, $charlist = " \t\n\r\0\x0B") {
288
                return ltrim($string, $charlist);
289 1
            },
290 1
            'rtrim' => function ($string, $charlist = " \t\n\r\0\x0B") {
291 1
                return rtrim($string, $charlist);
292
            },
293
            'str_repeat' => function ($string, $multiplier = 1) {
294
                return str_repeat($string, $multiplier);
295
            },
296
            'plural' => function ($string, $count = 2) {
297
                return str_plural($string, $count);
298
            },
299 1
            'strpad' => function ($string, $pad_length, $pad_string = ' ') {
300
                return str_pad($string, $pad_length, $pad_string, $pad_type = STR_PAD_BOTH);
301
            },
302
            'leftpad' => function ($string, $pad_length, $pad_string = ' ') {
303 1
                return str_pad($string, $pad_length, $pad_string, $pad_type = STR_PAD_LEFT);
304 1
            },
305 1
            'rightpad' => function ($string, $pad_length, $pad_string = ' ') {
306
                return str_pad($string, $pad_length, $pad_string, $pad_type = STR_PAD_RIGHT);
307
            },
308
            'rtl' => function ($string) {
309
                return strrev($string);
310
            },
311
            'strip_tags' => function ($string, $allow = '') {
312
                return strip_tags($string, $allow);
313 1
            },
314
            'var_dump' => function ($expression) {
315
                ob_start();
316
                var_dump($expression);
317 1
                $result = ob_get_clean();
318 1
319 1
                return $result;
320
            },
321
        ];
322
    }
323
324
    /**
325
     * Works like the config() helper function.
326
     *
327 1
     * @return array
328
     */
329
    private function getConfigFunction()
330
    {
331 1
        return [
332 1
            'config' => function ($key = null, $default = null) {
333 1
                return config($key, $default);
334
            },
335
        ];
336
    }
337
338
    /**
339
     * Works like the session() helper function.
340
     *
341 1
     * @return array
342
     */
343
    private function getSessionFunction()
344
    {
345 1
        return [
346 1
            'session' => function ($key = null) {
347 1
                return session($key);
348
            },
349 1
        ];
350 1
    }
351 1
352
    /**
353
     * Works like the trans() helper function.
354
     *
355
     * @return array
356
     */
357
    private function getTransFunction()
358
    {
359
        return [
360
            'trans' => function ($key = null, $parameters = []) {
361
                return trans($key, $parameters);
362
            },
363
        ];
364
    }
365
366 1
    /**
367
     * Dumps information about a variable.
368
     *
369 1
     * @return array
370 1
     */
371 1
    private function getVarDumpFunction()
372 1
    {
373
        return [
374
            'var_dump' => function ($expression) {
375 1
                ob_start();
376 1
                var_dump($expression);
377
                $result = ob_get_clean();
378
379
                return $result;
380 1
            },
381 1
        ];
382 1
    }
383 1
384 1
    /**
385 1
     * Create protected link with mailto:
386 1
     *
387 1
     * @param string $email Email to render.
388 1
     * @param bool $link If email should be rendered as link.
389 1
     * @param bool $protected If email should be protected.
390 1
     * @param string $text Link text. Render email by default.
391 1
     *
392 1
     * @see http://www.maurits.vdschee.nl/php_hide_email/
393 1
     *
394 1
     * @return string
395
     */
396 1
    private function hideEmail($email, $link = true, $protected = true, $text = null)
397 1
    {
398
        // email link text
399 1
        $linkText = $email;
400
        if ($text !== null) {
401
            $linkText = $text;
402
        }
403
404
        // if we want just unprotected link
405
        if (!$protected) {
406
            return $link ? '<a href="mailto:' . $email . '">' . $linkText . '</a>' : $linkText;
407
        }
408
409
        // turn on protection
410
        $character_set = '+-.0123456789@ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
411
        $key = str_shuffle($character_set);
412
        $cipher_text = '';
413
        $id = 'e' . rand(1, 999999999);
414 1
        for ($i = 0; $i < strlen($email); $i += 1) {
415
            $cipher_text .= $key[strpos($character_set, $email[$i])];
416
        }
417
        $script = 'var a="' . $key . '";var b=a.split("").sort().join("");var c="' . $cipher_text . '";var d="";';
418
        $script .= 'for(var e=0;e<c.length;e++)d+=b.charAt(a.indexOf(c.charAt(e)));';
419
        $script .= 'var y = d;';
420
        if ($text !== null) {
421
            $script .= 'var y = "'.$text.'";';
422
        }
423
        if ($link) {
424
            $script .= 'document.getElementById("' . $id . '").innerHTML="<a href=\\"mailto:"+d+"\\">"+y+"</a>"';
425
        } else {
426 1
            $script .= 'document.getElementById("' . $id . '").innerHTML=y';
427 1
        }
428
        $script = "eval(\"" . str_replace(array("\\", '"'), array("\\\\", '\"'), $script) . "\")";
429
        $script = '<script type="text/javascript">/*<![CDATA[*/' . $script . '/*]]>*/</script>';
430
431
        return '<span id="' . $id . '">[javascript protected email address]</span>' . $script;
432
    }
433
434
    /**
435
     * Appends this pattern: ? . {last modified date}
436
     * to an assets filename to force browser to reload
437
     * cached modified file.
438
     *
439
     * See: https://github.com/vojtasvoboda/oc-twigextensions-plugin/issues/25
440
     *
441
     * @return array
442
     */
443
    private function getFileRevision()
444
    {
445
        return [
446
            'revision' => function ($filename, $format = null) {
447
                // Remove http/web address from the file name if there is one to load it locally
448
                $prefix = url('/');
449
                $filename_ = trim(preg_replace('/^' . preg_quote($prefix, '/') . '/', '', $filename), '/');
450
                if (file_exists($filename_)) {
451
                    $timestamp = filemtime($filename_);
452
                    $prepend = ($format) ? date($format, $timestamp) : $timestamp;
453
454
                    return $filename . "?" . $prepend;
455
                }
456
457
                return $filename;
458
            },
459
        ];
460
    }
461
}
462