Completed
Push — format-currency ( fa34aa )
by Wouter
61:53
created

BaseTwigModifiers::formatNumber()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 2
eloc 4
nc 2
nop 2
1
<?php
2
3
namespace Common\Core\Twig\Extensions;
4
5
/*
6
 * This file is part of Fork CMS.
7
 *
8
 * For the full copyright and license information, please view the license
9
 * file that was distributed with this source code.
10
 */
11
12
/**
13
 * Contains Base Frontend-related custom modifiers.
14
 * These filters work independent of front/backend.
15
 */
16
class BaseTwigModifiers
17
{
18
    /**
19
     * Format a number as currency
20
     *    syntax: {{ $string|formatcurrency($currency, $decimals) }}.
21
     *
22
     * @param string $string   The string to form.
23
     * @param string $currency The currency to will be used to format the number.
24
     * @param int    $decimals The number of decimals to show.
25
     *
26
     * @return string
27
     */
28
    public static function formatCurrency($string, $currency = 'EUR', $decimals = null)
29
    {
30
        $decimals = ($decimals === null) ? 2 : (int) $decimals;
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $decimals. This often makes code more readable.
Loading history...
31
32
        // @later get settings from backend
33
        switch ($currency) {
34
            case 'EUR':
35
                $currency = '€';
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $currency. This often makes code more readable.
Loading history...
36
                break;
37
            default:
38
        }
39
40
        return $currency.'&nbsp;'.static::formatNumber($string, $decimals);
41
    }
42
43
    /**
44
     * Fallback for if our parent functions don't implement this method
45
     *
46
     * @param string $number
47
     * @param int $decimals
48
     *
49
     * @return string
50
     */
51
    public static function formatNumber($number, $decimals = null)
52
    {
53
        if ($decimals === null) {
54
            $decimals = 2;
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $decimals. This often makes code more readable.
Loading history...
55
        }
56
57
        return number_format((float) $number, $decimals, ',', '&nbsp;');
58
    }
59
60
    /**
61
     * Highlights all strings in <code> tags.
62
     *    syntax: {{ $string|highlight }}.
63
     *
64
     * @param string $string The string passed from the template.
65
     *
66
     * @return string
67
     */
68
    public static function highlightCode($string)
69
    {
70
        // regex pattern
71
        $pattern = '/<code>.*?<\/code>/is';
72
73
        // find matches
74
        if (preg_match_all($pattern, $string, $matches)) {
75
            // loop matches
76
            foreach ($matches[0] as $match) {
77
                // encase content in highlight_string
78
                $string = str_replace($match, highlight_string($match, true), $string);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $string. This often makes code more readable.
Loading history...
79
80
                // replace highlighted code tags in match
81
                $string = str_replace(array('&lt;code&gt;', '&lt;/code&gt;'), '', $string);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $string. This often makes code more readable.
Loading history...
82
            }
83
        }
84
85
        return $string;
86
    }
87
88
    /**
89
     * Get a random var between a min and max
90
     *    syntax: {{ rand($min, $max) }}.
91
     *
92
     * @param int $min The minimum random number.
93
     * @param int $max The maximum random number.
94
     *
95
     * @return int
96
     */
97
    public static function random($min, $max)
98
    {
99
        $min = (int) $min;
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $min. This often makes code more readable.
Loading history...
100
        $max = (int) $max;
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $max. This often makes code more readable.
Loading history...
101
102
        return rand($min, $max);
103
    }
104
105
    /**
106
     * Convert a multi line string into a string without newlines so it can be handles by JS
107
     * 		syntax: {{ $string|stripnewlines }}.
108
     *
109
     * @param string $string The variable that should be processed.
110
     *
111
     * @return string
112
     */
113
    public static function stripNewlines($string)
114
    {
115
        return str_replace(array("\r\n", "\n", "\r"), ' ', $string);
116
    }
117
118
    /**
119
     * Transform the string to uppercase.
120
     * 		syntax: {{ $string|uppercase }}.
121
     *
122
     * @param string $string The string that you want to apply this method on.
123
     *
124
     * @return string The string, completly uppercased.
125
     */
126
    public static function uppercase($string)
127
    {
128
        return mb_convert_case($string, MB_CASE_UPPER, \Spoon::getCharset());
129
    }
130
131
    /**
132
     * Makes this string lowercase.
133
     * 		syntax: {{ $string|lowercase }}.
134
     *
135
     *
136
     * @param string $string The string that you want to apply this method on.
137
     *
138
     * @return string The string, completely lowercased.
139
     */
140
    public static function lowercase($string)
141
    {
142
        return mb_convert_case($string, MB_CASE_LOWER, \Spoon::getCharset());
143
    }
144
145
    /**
146
     * snakeCase Converter.
147
     * 		syntax: {{ $string|snakecase }}.
148
     *
149
     * @internal Untested, Needs testing
150
     *
151
     * @param string $string
152
     *
153
     * @return string
154
     */
155
    public static function snakeCase($string)
156
    {
157
        return ltrim(strtolower(preg_replace('/[A-Z]/', '_$0', $string)), '_');
158
    }
159
160
    /**
161
     * CamelCase Converter.
162
     * 		syntax: {{ $string|camelcase }}.
163
     *
164
     * @internal Untested, Needs testing
165
     *
166
     * @param string $string
167
     *
168
     * @return string
169
     */
170
    public static function camelCase($string)
171
    {
172
        // non-alpha and non-numeric characters become spaces
173
        $string = preg_replace('/[^a-z0-9'.implode('', []).']+/i', ' ', $string);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $string. This often makes code more readable.
Loading history...
174
        $string = trim($string);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $string. This often makes code more readable.
Loading history...
175
        // uppercase the first character of each word
176
        $string = ucwords($string);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $string. This often makes code more readable.
Loading history...
177
        $string = str_replace(' ', '', $string);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $string. This often makes code more readable.
Loading history...
178
        $string = lcfirst($string);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $string. This often makes code more readable.
Loading history...
179
180
        return $string;
181
    }
182
183
    /**
184
     * Formats a language specific date.
185
     * 		syntax: {{ $timestamp|spoondate($format, $language) }}.
186
     *
187
     * @param mixed            $timestamp The timestamp or date that you want to apply the format to.
188
     * @param string[optional] $format    The optional format that you want to apply on the provided timestamp.
189
     * @param string[optional] $language  The optional language that you want this format in (Check SpoonLocale for the possible languages).
190
     *
191
     * @return string The formatted date according to the timestamp, format and provided language.
192
     */
193
    public static function spoonDate($timestamp, $format = 'Y-m-d H:i:s', $language = 'en')
194
    {
195
        if (is_string($timestamp) && !is_numeric($timestamp)) {
196
            // use strptime if you want to restrict the input format
197
            $timestamp = strtotime($timestamp);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $timestamp. This often makes code more readable.
Loading history...
198
        }
199
200
        return \SpoonDate::getDate($format, $timestamp, $language);
201
    }
202
203
    /**
204
     * Shows a v or x to indicate the boolean state (Y|N, j|n, true|false).
205
     * 		syntax: {{ showbool($status, $reverse) }}.
206
     *
207
     * @param string|bool $status
208
     * @param bool        $reverse show the opposite of the status
209
     *
210
     * @return string
211
     */
212
    public static function showBool($status, $reverse = false)
213
    {
214
        $showTrue = '<strong style="color:green">&#10003;</strong>';
215
        $showFalse = '<strong style="color:red">&#10008;</strong>';
216
217
        if ($reverse) {
218
            if ($status === 'Y' || $status === 'y' || $status === 1 || $status === '1' || $status === true) {
219
                return $showFalse;
220
            }
221
222
            if ($status === 'N' || $status === 'n' || $status === 0 || $status === '0' || $status === false) {
223
                return $showTrue;
224
            }
225
226
            return $status;
227
        }
228
229
        if ($status === 'Y' || $status === 'y' || $status === 1 || $status === '1' || $status === true) {
230
            return $showTrue;
231
        }
232
233
        if ($status === 'N' || $status === 'n' || $status === 0 || $status === '0' || $status === false) {
234
            return $showFalse;
235
        }
236
237
        return $status;
238
    }
239
240
    /**
241
     * Truncate a string
242
     *    syntax: {{ $string|truncate($max-length, $append-hellip, $closest-word) }}.
243
     *
244
     * @param string $string      The string passed from the template.
245
     * @param int    $length      The maximum length of the truncated string.
246
     * @param bool   $useHellip   Should a hellip be appended if the length exceeds the requested length?
247
     * @param bool   $closestWord Truncate on exact length or on closest word?
248
     *
249
     * @return string
250
     */
251
    public static function truncate($string = null, $length, $useHellip = true, $closestWord = false)
252
    {
253
        // remove special chars, all of them, also the ones that shouldn't be there.
254
        $string = \SpoonFilter::htmlentitiesDecode($string, null, ENT_QUOTES);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $string. This often makes code more readable.
Loading history...
255
256
        // remove HTML
257
        $string = strip_tags($string);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $string. This often makes code more readable.
Loading history...
258
259
        // less characters
260
        if (mb_strlen($string) <= $length) {
261
            return \SpoonFilter::htmlspecialchars($string);
262
        } else {
263
            // more characters
264
            // hellip is seen as 1 char, so remove it from length
265
            if ($useHellip) {
266
                $length = $length - 1;
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $length. This often makes code more readable.
Loading history...
267
            }
268
269
            // truncate
270
            if ($closestWord) {
271
                $string = mb_substr($string, 0, strrpos(substr($string, 0, $length + 1), ' '), 'UTF-8');
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $string. This often makes code more readable.
Loading history...
272
            } else {
273
                $string = mb_substr($string, 0, $length, 'UTF8');
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $string. This often makes code more readable.
Loading history...
274
            }
275
276
            // add hellip
277
            if ($useHellip) {
278
                $string .= '…';
279
            }
280
281
            // return
282
            return \SpoonFilter::htmlspecialchars($string, ENT_QUOTES);
283
        }
284
    }
285
}
286