Passed
Push — master ( e6feb1...05db97 )
by Vojta
20:16 queued 09:59
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 System\Classes\PluginBase;
7
use Twig_Extension_StringLoader;
8
use Twig_Extensions_Extension_Array;
9
use Twig_Extensions_Extension_Date;
10
use Twig_Extensions_Extension_Intl;
11
use Twig_Extensions_Extension_Text;
12
use VojtaSvoboda\TwigExtensions\Classes\TimeDiffTranslator;
13
14
/**
15
 * Twig Extensions Plugin.
16
 *
17
 * @see http://twig.sensiolabs.org/doc/extensions/index.html#extensions-install
18
 */
19
class Plugin extends PluginBase
20
{
21
    /**
22
     * Returns information about this plugin.
23
     *
24
     * @return array
25
     */
26
    public function pluginDetails()
27
    {
28
        return [
29
            'name'        => 'Twig Extensions',
30
            'description' => 'Add more Twig filters to your templates.',
31
            'author'      => 'Vojta Svoboda',
32
            'icon'        => 'icon-plus',
33
            'homepage'    => 'https://github.com/vojtasvoboda/oc-twigextensions-plugin',
34
        ];
35
    }
36
37 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...
38
    {
39
        $this->app->singleton('time_diff_translator', function($app) {
40
            $loader = $app->make('translation.loader');
41
            $locale = $app->config->get('app.locale');
42
            $translator = $app->make(TimeDiffTranslator::class, [$loader, $locale]);
43
            $translator->setFallback($app->config->get('app.fallback_locale'));
44
45
            return $translator;
46
        });
47
    }
48
49
    /**
50
     * Add Twig extensions.
51
     *
52
     * @see Text extensions http://twig.sensiolabs.org/doc/extensions/text.html
53
     * @see Intl extensions http://twig.sensiolabs.org/doc/extensions/intl.html
54
     * @see Array extension http://twig.sensiolabs.org/doc/extensions/array.html
55
     * @see Time extension http://twig.sensiolabs.org/doc/extensions/date.html
56
     *
57
     * @return array
58
     */
59 1
    public function registerMarkupTags()
60
    {
61 1
        $filters = [];
62 1
        $functions = [];
63
64
        // init Twig
65 1
        $twig = $this->app->make('twig.environment');
66
67
        // add String Loader functions
68 1
        $functions += $this->getStringLoaderFunctions($twig);
69
70
        // add Config function
71 1
        $functions += $this->getConfigFunction();
72
73
        // add Session function
74 1
        $functions += $this->getSessionFunction();
75
76
        // add Trans function
77 1
        $functions += $this->getTransFunction();
78
79
        // add var_dump function
80 1
        $functions += $this->getVarDumpFunction();
81
82
        // add Text extensions
83 1
        $filters += $this->getTextFilters($twig);
84
85
        // add Intl extensions if php5-intl installed
86 1
        if (class_exists('IntlDateFormatter')) {
87 1
            $filters += $this->getLocalizedFilters($twig);
88 1
        }
89
90
        // add Array extensions
91 1
        $filters += $this->getArrayFilters();
92
93
        // add Time extensions
94 1
        $filters += $this->getTimeFilters($twig);
95
96
        // add Mail filters
97 1
        $filters += $this->getMailFilters();
98
99
        // add PHP functions
100 1
        $filters += $this->getPhpFunctions();
101
102
        return [
103 1
            'filters'   => $filters,
104 1
            'functions' => $functions,
105 1
        ];
106
    }
107
108
    /**
109
     * Returns String Loader functions.
110
     *
111
     * @param \Twig_Environment $twig
112
     *
113
     * @return array
114
     */
115 1
    private function getStringLoaderFunctions($twig)
116
    {
117 1
        $stringLoader = new Twig_Extension_StringLoader();
118 1
        $stringLoaderFunc = $stringLoader->getFunctions();
119
120
        return [
121
            'template_from_string' => function($template) use ($twig, $stringLoaderFunc) {
122 1
                $callable = $stringLoaderFunc[0]->getCallable();
123 1
                return $callable($twig, $template);
124
            }
125 1
        ];
126
    }
127
128
    /**
129
     * Returns Text filters.
130
     *
131
     * @param \Twig_Environment $twig
132
     *
133
     * @return array
134
     */
135 3
    private function getTextFilters($twig)
136
    {
137 1
        $textExtension = new Twig_Extensions_Extension_Text();
138 1
        $textFilters = $textExtension->getFilters();
139
140
        return [
141
            'truncate' => function($value, $length = 30, $preserve = false, $separator = '...') use ($twig, $textFilters) {
142 3
                $callable = $textFilters[0]->getCallable();
143 3
                return $callable($twig, $value, $length, $preserve, $separator);
144 1
            },
145
            'wordwrap' => function($value, $length = 80, $separator = "\n", $preserve = false) use ($twig, $textFilters) {
146 1
                $callable = $textFilters[1]->getCallable();
147 1
                return $callable($twig, $value, $length, $separator, $preserve);
148
            }
149 1
        ];
150
    }
151
152
    /**
153
     * Returns Intl filters.
154
     *
155
     * @param \Twig_Environment $twig
156
     *
157
     * @return array
158
     */
159 1
    private function getLocalizedFilters($twig)
160
    {
161 1
        $intlExtension = new Twig_Extensions_Extension_Intl();
162 1
        $intlFilters = $intlExtension->getFilters();
163
164
        return [
165
            'localizeddate' => function($date, $dateFormat = 'medium', $timeFormat = 'medium', $locale = null, $timezone = null, $format = null) use ($twig, $intlFilters) {
166
                $callable = $intlFilters[0]->getCallable();
167
                return $callable($twig, $date, $dateFormat, $timeFormat, $locale, $timezone, $format);
168 1
            },
169
            'localizednumber' => function($number, $style = 'decimal', $type = 'default', $locale = null) use ($twig, $intlFilters) {
170
                $callable = $intlFilters[1]->getCallable();
171
                return $callable($number, $style, $type, $locale);
172 1
            },
173
            'localizedcurrency' => function($number, $currency = null, $locale = null) use ($twig, $intlFilters) {
174
                $callable = $intlFilters[2]->getCallable();
175
                return $callable($number, $currency, $locale);
176
            }
177 1
        ];
178
    }
179
180
    /**
181
     * Returns Array filters.
182
     *
183
     * @return array
184
     */
185 2
    private function getArrayFilters()
186
    {
187 1
        $arrayExtension = new Twig_Extensions_Extension_Array();
188 1
        $arrayFilters = $arrayExtension->getFilters();
189
190
        return [
191
            'shuffle' => function($array) use ($arrayFilters) {
192 2
                $callable = $arrayFilters[0]->getCallable();
193 2
                return $callable($array);
194
            }
195 1
        ];
196
    }
197
198
    /**
199
     * Returns Date filters.
200
     *
201
     * @param \Twig_Environment $twig
202
     *
203
     * @return array
204
     */
205 1
    private function getTimeFilters($twig)
206
    {
207 1
        $translator = $this->app->make('time_diff_translator');
208 1
        $timeExtension = new Twig_Extensions_Extension_Date($translator);
209 1
        $timeFilters = $timeExtension->getFilters();
210
211
        return [
212
            'time_diff' => function($date, $now = null) use ($twig, $timeFilters) {
213
                $callable = $timeFilters[0]->getCallable();
214
                return $callable($twig, $date, $now);
215
            }
216 1
        ];
217
    }
218
219
    /**
220
     * Returns mail filters.
221
     *
222
     * @return array
223
     */
224 1
    private function getMailFilters()
225
    {
226
        return [
227
            'mailto' => function($string, $link = true, $protected = true, $text = null) {
228 1
                return $this->hideEmail($string, $link, $protected, $text);
229
            }
230 1
        ];
231
    }
232
233
    /**
234
     * Returns plain PHP functions.
235
     *
236
     * @return array
237
     */
238 1
    private function getPhpFunctions()
239
    {
240
        return [
241
            'strftime' => function($time, $format = '%d.%m.%Y %H:%M:%S') {
242 1
                $timeObj = new Carbon($time);
243 1
                return strftime($format, $timeObj->getTimestamp());
244 1
            },
245
            'uppercase' => function($string) {
246 1
                return mb_convert_case($string, MB_CASE_UPPER, "UTF-8");
247 1
            },
248
            'lowercase' => function($string) {
249 1
                return mb_convert_case($string, MB_CASE_LOWER, "UTF-8");
250 1
            },
251
            'ucfirst' => function($string) {
252 1
                return mb_convert_case($string, MB_CASE_TITLE, "UTF-8");
253 1
            },
254
            'lcfirst' => function($string) {
255 1
                return lcfirst($string);
256 1
            },
257
            'ltrim' => function($string, $charlist = " \t\n\r\0\x0B") {
258 1
                return ltrim($string, $charlist);
259 1
            },
260
            'rtrim' => function($string, $charlist = " \t\n\r\0\x0B") {
261 1
                return rtrim($string, $charlist);
262 1
            },
263
            'str_repeat' => function($string, $multiplier = 1) {
264 1
                return str_repeat($string, $multiplier);
265 1
            },
266
            'plural' => function($string, $count = 2) {
267 1
                return str_plural($string, $count);
268 1
            },
269
            'strpad' => function($string, $pad_length, $pad_string = ' ') {
270 1
                return str_pad($string, $pad_length, $pad_string, $pad_type = STR_PAD_BOTH);
271 1
            },
272
            'leftpad' => function($string, $pad_length, $pad_string = ' ') {
273 1
                return str_pad($string, $pad_length, $pad_string, $pad_type = STR_PAD_LEFT);
274 1
            },
275
            'rightpad' => function($string, $pad_length, $pad_string = ' ') {
276 1
                return str_pad($string, $pad_length, $pad_string, $pad_type = STR_PAD_RIGHT);
277 1
            },
278
            'rtl' => function($string) {
279 1
                return strrev($string);
280 1
            },
281
            'var_dump' => function($expression) {
282 1
                ob_start();
283 1
                var_dump($expression);
284 1
                $result = ob_get_clean();
285
286 1
                return $result;
287 1
            },
288 1
        ];
289
    }
290
291
    /**
292
     * Works like the config() helper function.
293
     *
294
     * @return array
295
     */
296 1
    private function getConfigFunction()
297
    {
298
        return [
299
            'config' => function($key = null, $default = null) {
300 1
                return config($key, $default);
301 1
            },
302 1
        ];
303
    }
304
305
    /**
306
     * Works like the session() helper function.
307
     *
308
     * @return array
309
     */
310 1
    private function getSessionFunction()
311
    {
312
        return [
313
            'session' => function($key = null) {
314 1
                return session($key);
315 1
            },
316 1
        ];
317
    }
318
319
    /**
320
     * Works like the trans() helper function.
321
     *
322
     * @return array
323
     */
324 1
    private function getTransFunction()
325
    {
326
        return [
327
            'trans' => function($key = null) {
328 1
                return trans($key);
329 1
            },
330 1
        ];
331
    }
332
333
    /**
334
     * Dumps information about a variable.
335
     *
336
     * @return array
337
     */
338
    private function getVarDumpFunction()
339
    {
340
        return [
341 1
            'var_dump' => function($expression) {
342 1
                ob_start();
343 1
                var_dump($expression);
344 1
                $result = ob_get_clean();
345
346 1
                return $result;
347 1
            },
348 1
        ];
349
    }
350
351
    /**
352
     * Create protected link with mailto:
353
     *
354
     * @param string $email Email to render.
355
     * @param bool $link If email should be rendered as link.
356
     * @param bool $protected If email should be protected.
357
     * @param string $text Link text. Render email by default.
358
     *
359
     * @see http://www.maurits.vdschee.nl/php_hide_email/
360
     *
361
     * @return string
362
     */
363 1
    private function hideEmail($email, $link = true, $protected = true, $text = null)
364
    {
365
        // email link text
366 1
        $linkText = $email;
367 1
        if ($text !== null) {
368 1
            $linkText = $text;
369 1
        }
370
371
        // if we want just unprotected link
372 1
        if (!$protected) {
373 1
            return $link ? '<a href="mailto:' . $email . '">' . $linkText . '</a>' : $linkText;
374
        }
375
376
        // turn on protection
377 1
        $character_set = '+-.0123456789@ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
378 1
        $key = str_shuffle($character_set);
379 1
        $cipher_text = '';
380 1
        $id = 'e' . rand(1, 999999999);
381 1
        for ($i = 0; $i < strlen($email); $i += 1) $cipher_text .= $key[strpos($character_set, $email[$i])];
382 1
        $script = 'var a="' . $key . '";var b=a.split("").sort().join("");var c="' . $cipher_text . '";var d="";';
383 1
        $script .= 'for(var e=0;e<c.length;e++)d+=b.charAt(a.indexOf(c.charAt(e)));';
384 1
        $script .= 'var y = d;';
385 1
        if ($text !== null) {
386 1
            $script .= 'var y = "'.$text.'";';
387 1
        }
388 1
        if ($link) {
389 1
            $script .= 'document.getElementById("' . $id . '").innerHTML="<a href=\\"mailto:"+d+"\\">"+y+"</a>"';
390 1
        } else {
391 1
            $script .= 'document.getElementById("' . $id . '").innerHTML=y';
392
        }
393 1
        $script = "eval(\"" . str_replace(array("\\", '"'), array("\\\\", '\"'), $script) . "\")";
394 1
        $script = '<script type="text/javascript">/*<![CDATA[*/' . $script . '/*]]>*/</script>';
395
396 1
        return '<span id="' . $id . '">[javascript protected email address]</span>' . $script;
397
    }
398
}
399