Test Failed
Pull Request — master (#53)
by
unknown
05:27
created

Plugin::getRedirectFunction()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 2

Importance

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