Completed
Push — master ( 28f695...c018b2 )
by Vojta
10:01
created

Plugin::getConfigFunction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 0
crap 1
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
 * - add more Twig filters to your template
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
    /**
38
     * Add Twig extensions
39
     *
40
     * @see Text extensions http://twig.sensiolabs.org/doc/extensions/text.html
41
     * @see Intl extensions http://twig.sensiolabs.org/doc/extensions/intl.html
42
     * @see Array extension http://twig.sensiolabs.org/doc/extensions/array.html
43
     * @see Time extension http://twig.sensiolabs.org/doc/extensions/date.html
44
     *
45
     * @return array
46
     */
47 1
    public function registerMarkupTags()
48
    {
49 1
        $filters = [];
50 1
        $functions = [];
51
52
        // init Twig
53 1
        $twig = App::make('twig.environment');
54
55
        // add String Loader functions
56 1
        $functions += $this->getStringLoaderFunctions($twig);
57
58
        // add Config function
59 1
        $functions += $this->getConfigFunction();
60
61
        // add Text extensions
62 1
        $filters += $this->getTextFilters($twig);
63
64
        // add Intl extensions if php5-intl installed
65 1
        if (class_exists('IntlDateFormatter')) {
66 1
            $filters += $this->getLocalizedFilters($twig);
67 1
        }
68
69
        // add Array extensions
70 1
        $filters += $this->getArrayFilters();
71
72
        // add Time extensions
73 1
        $filters += $this->getTimeFilters($twig);
74
75
        // add PHP functions
76 1
        $filters += $this->getPhpFunctions();
77
78
        return [
79 1
            'filters'   => $filters,
80
            'functions' => $functions
81 1
        ];
82
    }
83
84
    /**
85
     * Returns String Loader functions
86
     *
87
     * @param \Twig_Environment $twig
88
     *
89
     * @return array
90
     */
91 1
    private function getStringLoaderFunctions($twig)
92
    {
93 1
        $stringLoader = new Twig_Extension_StringLoader();
94 1
        $stringLoaderFunc = $stringLoader->getFunctions();
95
96
        return [
97
            'template_from_string' => function($template) use ($twig, $stringLoaderFunc) {
98 1
                $callable = $stringLoaderFunc[0]->getCallable();
99 1
                return $callable($twig, $template);
100
            }
101 1
        ];
102
    }
103
104
    /**
105
     * Returns Text filters
106
     *
107
     * @param \Twig_Environment $twig
108
     *
109
     * @return array
110
     */
111 3
    private function getTextFilters($twig)
112
    {
113 1
        $textExtension = new Twig_Extensions_Extension_Text();
114 1
        $textFilters = $textExtension->getFilters();
115
116
        return [
117 View Code Duplication
            'truncate' => function($value, $length = 30, $preserve = false, $separator = '...') use ($twig, $textFilters) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across 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...
118 3
                $callable = $textFilters[0]->getCallable();
119 3
                return $callable($twig, $value, $length, $preserve, $separator);
120 1
            },
121 View Code Duplication
            'wordwrap' => function($value, $length = 80, $separator = "\n", $preserve = false) use ($twig, $textFilters) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across 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...
122 1
                $callable = $textFilters[1]->getCallable();
123 1
                return $callable($twig, $value, $length, $separator, $preserve);
124
            }
125 1
        ];
126
    }
127
128
    /**
129
     * Returns Intl filters
130
     *
131
     * @param \Twig_Environment $twig
132
     *
133
     * @return array
134
     */
135 1
    private function getLocalizedFilters($twig)
136
    {
137 1
        $intlExtension = new Twig_Extensions_Extension_Intl();
138 1
        $intlFilters = $intlExtension->getFilters();
139
140
        return [
141
            'localizeddate' => function($date, $dateFormat = 'medium', $timeFormat = 'medium', $locale = null, $timezone = null, $format = null) use ($twig, $intlFilters) {
142
                $callable = $intlFilters[0]->getCallable();
143
                return $callable($twig, $date, $dateFormat, $timeFormat, $locale, $timezone, $format);
144 1
            },
145
            'localizednumber' => function($number, $style = 'decimal', $type = 'default', $locale = null) use ($twig, $intlFilters) {
146
                $callable = $intlFilters[1]->getCallable();
147
                return $callable($number, $style, $type, $locale);
148 1
            },
149
            'localizedcurrency' => function($number, $currency = null, $locale = null) use ($twig, $intlFilters) {
150
                $callable = $intlFilters[2]->getCallable();
151
                return $callable($number, $currency, $locale);
152
            }
153 1
        ];
154
    }
155
156
    /**
157
     * Returns Array filters
158
     *
159
     * @return array
160
     */
161 2
    private function getArrayFilters()
162
    {
163 1
        $arrayExtension = new Twig_Extensions_Extension_Array();
164 1
        $arrayFilters = $arrayExtension->getFilters();
165
166
        return [
167
            'shuffle' => function($array) use ($arrayFilters) {
168 2
                $callable = $arrayFilters[0]->getCallable();
169 2
                return $callable($array);
170
            }
171 1
        ];
172
    }
173
174
    /**
175
     * Returns Date filters
176
     *
177
     * @param \Twig_Environment $twig
178
     *
179
     * @return array
180
     */
181 1
    private function getTimeFilters($twig)
182
    {
183 1
        $timeExtension = new Twig_Extensions_Extension_Date();
184 1
        $timeFilters = $timeExtension->getFilters();
185
186
        return [
187
            'time_diff' => function($date, $now = null) use ($twig, $timeFilters) {
188 1
                $callable = $timeFilters[0]->getCallable();
189 1
                return $callable($twig, $date, $now);
190
            }
191 1
        ];
192
    }
193
194
    /**
195
     * Returns plain PHP functions
196
     *
197
     * @return array
198
     */
199 1
    private function getPhpFunctions()
200
    {
201
        return [
202
            'strftime' => function($time, $format = '%d.%m.%Y %H:%M:%S') {
203 1
                $timeObj = new Carbon($time);
204 1
                return strftime($format, $timeObj->getTimestamp());
205 1
            },
206
            'uppercase' => function($string) {
207 1
                return mb_convert_case($string, MB_CASE_UPPER, "UTF-8");
208 1
            },
209
            'lowercase' => function($string) {
210 1
                return mb_convert_case($string, MB_CASE_LOWER, "UTF-8");
211 1
            },
212
            'ucfirst' => function($string) {
213 1
                return mb_convert_case($string, MB_CASE_TITLE, "UTF-8");
214 1
            },
215
            'lcfirst' => function($string) {
216 1
                return lcfirst($string);
217 1
            },
218
            'ltrim' => function($string, $charlist = " \t\n\r\0\x0B") {
219 1
                return ltrim($string, $charlist);
220 1
            },
221
            'rtrim' => function($string, $charlist = " \t\n\r\0\x0B") {
222 1
                return rtrim($string, $charlist);
223 1
            },
224
            'str_repeat' => function($string, $multiplier = 1) {
225 1
                return str_repeat($string, $multiplier);
226 1
            },
227
            'plural' => function($string, $count = 2) {
228 1
                return str_plural($string, $count);
229 1
            },
230
            'strpad' => function($string, $pad_length, $pad_string = ' ') {
231 1
                return str_pad($string, $pad_length, $pad_string, $pad_type = STR_PAD_BOTH);
232 1
            },
233
            'leftpad' => function($string, $pad_length, $pad_string = ' ') {
234 1
                return str_pad($string, $pad_length, $pad_string, $pad_type = STR_PAD_LEFT);
235 1
            },
236
            'rightpad' => function($string, $pad_length, $pad_string = ' ') {
237 1
                return str_pad($string, $pad_length, $pad_string, $pad_type = STR_PAD_RIGHT);
238 1
            },
239 1
        ];
240
    }
241
242
    /**
243
     * Works like the config() function
244
     *
245
     * @return array
246
     */
247
    private function getConfigFunction()
248
    {
249
        return [
250 1
            'config' => function($key = null, $default = null) {
251 1
                return config($key, $default);
252 1
            },
253 1
        ];
254
    }
255
}
256