Completed
Push — master ( e829a4...a4554a )
by Vojta
09:22
created

Plugin::getPhpFunctions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 52
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 34
CRAP Score 1

Importance

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