Utils   A
last analyzed

Complexity

Total Complexity 31

Size/Duplication

Total Lines 286
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 6
Bugs 0 Features 0
Metric Value
wmc 31
c 6
b 0
f 0
lcom 0
cbo 0
dl 0
loc 286
rs 9.8

9 Methods

Rating   Name   Duplication   Size   Complexity  
A getContent() 0 4 1
A checkValue() 0 4 2
A unescapeProperties() 0 8 2
B fixArrayValues() 0 26 6
B removeQuotes() 0 10 5
A trimArrayElements() 0 10 1
A stripBackslashes() 0 8 2
C trimWhitespace() 0 89 11
A __toString() 0 4 1
1
<?php
2
3
/**
4
 * Konfig.
5
 *
6
 * Yet another simple configuration loader library.
7
 *
8
 * PHP version 5
9
 *
10
 * @category Library
11
 * @package  Konfig
12
 * @author   Xeriab Nabil (aka KodeBurner) <[email protected]>
13
 * @license  https://raw.github.com/xeriab/konfig/master/LICENSE MIT
14
 * @link     https://xeriab.github.io/projects/konfig
15
 */
16
17
namespace Exen\Konfig;
18
19
use Closure;
20
21
/**
22
 * Konfig's utilities class
23
 *
24
 * @category Main
25
 * @package  Konfig
26
 * @author   Xeriab Nabil (aka KodeBurner) <[email protected]>
27
 * @license  https://raw.github.com/xeriab/konfig/master/LICENSE MIT
28
 * @link     https://xeriab.github.io/projects/konfig
29
 */
30
final class Utils
31
{
32
    /**
33
     * Get the content of given file and returns the results.
34
     *
35
     * @param string $file The path to the file
36
     *
37
     * @return             string The results of the include
38
     * @since              0.2.4
39
     * @codeCoverageIgnore
40
     */
41
    public static function getContent($file = null)
42
    {
43
        return file_get_contents(realpath($file));
44
    }
45
46
    /**
47
     * Takes a value and checks if it's a Closure or not, if it's a Closure it
48
     * will return the result of the closure, if not, it will simply return the
49
     * value.
50
     *
51
     * @param string|null $var The value to get
52
     *
53
     * @return             mixed
54
     * @since              0.1.0
55
     * @codeCoverageIgnore
56
     */
57
    public static function checkValue($var = null)
58
    {
59
        return ($var instanceof Closure) ? $var() : $var;
60
    }
61
62
    /**
63
     * {@inheritdoc}
64
     *
65
     * @param array $array Configuration items
66
     *
67
     * @return array
68
     *
69
     * @since              0.2.4
70
     * @codeCoverageIgnore
71
     */
72
    public static function unescapeProperties(array &$array)
73
    {
74
        foreach ($array as $key => $value) {
75
            $array[$key] = str_replace('\=', '=', $value);
76
        }
77
78
        // return $array;
79
    }
80
81
    /**
82
     * Fix value types of the given array.
83
     *
84
     * @param array $array The Array to fix
85
     *
86
     * @return             array
87
     * @since              0.2.4
88
     * @codeCoverageIgnore
89
     */
90
    public static function fixArrayValues(array &$array)
91
    {
92
        foreach ($array as $key => $value) {
93
            // Numerical fix
94
            if (preg_match('/^[1-9][0-9]*$/', $value)) {
95
                $array[$key] = intval($value);
96
            }
97
98
            // Boolean and semi boolean fix
99
            if (preg_match('/^true|false|TRUE|FALSE|on|off|ON|OFF*$/', $value)) {
100
                $array[$key] = boolval($value);
101
            }
102
103
            // Double fix
104
            if (preg_match('/^[0-9]*[\.]{1}[0-9]*$/', $value)) {
105
                $array[$key] = doubleval($value);
106
            }
107
108
            // Float fix
109
            if (preg_match('/^[0-9]*[\.]{1}[0-9-]*$/', $value)) {
110
                $array[$key] = floatval($value);
111
            }
112
        }
113
114
        // return $array;
115
    }
116
117
    /**
118
     * Remove quotes.
119
     *
120
     * @param string $string The string to remove quotes from
121
     *
122
     * @return             string
123
     * @since              0.2.4
124
     * @codeCoverageIgnore
125
     */
126
    public static function removeQuotes($string = null)
127
    {
128
        if (substr($string, -1) === '"' && substr($string, 0, 1) === '"') {
129
            $string = substr($string, 1, -1);
130
        } elseif (substr($string, -1) === '\'' && substr($string, 0, 1) === '\'') {
131
            $string = substr($string, 1, -1);
132
        }
133
134
        return $string;
135
    }
136
137
    /**
138
     * Trim array elements.
139
     *
140
     * @param array $array Configuration items
141
     *
142
     * @return             mixed
143
     * @since              0.2.4
144
     * @codeCoverageIgnore
145
     */
146
    public static function trimArrayElements(array &$array)
147
    {
148
        $cb = function ($el) {
149
            return trim($el);
150
        };
151
152
        $array = array_map($cb, $array);
153
154
        // return $content;
155
    }
156
157
    /**
158
     * Strip Backslashes from given array's elements.
159
     *
160
     * @param array $array Array to work with
161
     *
162
     * @return             array
163
     * @since              0.2.4
164
     * @codeCoverageIgnore
165
     */
166
    public static function stripBackslashes(array &$array)
167
    {
168
        foreach ($array as $key => $value) {
169
            $array[$key] = str_replace('\=', '=', $value);
170
        }
171
172
        // return $array;
173
    }
174
175
    // Barrowed from: https://github.com/fvsch/php-trim-whitespace
176
177
    /**
178
     * Trim whitespace in multiline text
179
     *
180
     * By default, removes leading and trailing whitespace, collapses all other
181
     * space sequences, and removes blank lines. Most of this can be controlled
182
     * by passing an options array with the following keys:
183
     *
184
     *   - leading (bool, true): should we trim leading whitespace?
185
     *   - inside (bool, true): should we collapse spaces within a line
186
     *     (not leading whitespace)?
187
     *   - blankLines (int, 0): max number of consecutive blank lines;
188
     *     use false to disable.
189
     *   - tabWidth (int, 4): number of spaces to use when replacing tabs.
190
     *
191
     * The default settings can be used as basic minification for HTML text
192
     * (except for preformatted text!). This function can  be used remove extra
193
     * whitespace generated by a mix of PHP and HTML or by a template engine.
194
     *
195
     * This function forces two behaviors:
196
     *   - Trailing whitespace will be removed, always.
197
     *   - Tab characters will be replaced by space characters, always
198
     *     (for performance reasons).
199
     *
200
     * This was summarily tested on PHP 5.6 and PHP 7 to be as fast as possible,
201
     * and tested against different approches (e.g. splitting as an array and using
202
     * PHP’s trim function). The fastest solution found was using str_replace when
203
     * possible and preg_replace otherwise with very simple regexps to avoid big
204
     * perf costs. The current implementation should be, if not the fastest
205
     * possible, probably close enough.
206
     *
207
     * @param string $string  String to trim
208
     * @param array  $options Options
209
     *
210
     * @return             string
211
     * @since              0.2.5
212
     * @codeCoverageIgnore
213
     */
214
    public static function trimWhitespace($string, array $options = [])
215
    {
216
        if (!is_string($string)) {
217
            return '';
218
        }
219
220
        $o = array_merge(
221
            [
222
                'leading' => true,
223
                'inside' => true,
224
                'blankLines' => 0,
225
                'tabWidth' => 4,
226
            ],
227
            $options
228
        );
229
230
        // Looking for spaces *and* tab characters is way too costly
231
        // (running times go x4 or x10) so we forcefully replace tab characters
232
        // with spaces, but make it configurable.
233
        $tabw = $o['tabWidth'];
234
235
        if (!is_int($tabw) || $tabw < 1 || $tabw > 8) {
236
            $tabw = 4;
237
        }
238
239
        // Replacement patterns should be applied in a specific order
240
        $patterns = [];
241
242
        // Trim leading whitespace first (if active). In typical scenarios,
243
        // especially for indented HTML, this will remove of the target whitespace
244
        // and it turns out to be really quick.
245
        if ($o['leading']) {
246
            $patterns[] = ['/^ {2,}/m', ''];
247
        }
248
249
        // Always trim at the end. Warning: this seems to be the costlier
250
        // operation, perhaps because looking ahead is harder?
251
        $patterns[] = ['/ +$/m', ''];
252
253
        // Collapse space sequences inside lines (excluding leading/trailing)
254
        if ($o['inside']) {
255
            // No leading spaces? We can avoid a very costly condition!
256
            // Using a look-behind (or similar solutions) seems to make the whole
257
            // function go 2x-4x slower (PHP7) or up to 10x slower (PHP 5.6),
258
            // except on very big strings where whatever perf penalty was incurred
259
            // seems to be more limited (or at least not exponential).
260
            $spaces = ($o['leading'] ? ' ' : '(?<=\b) ') . '{2,}';
261
            $patterns[] = ['/' . $spaces . '/', ' '];
262
        }
263
264
        // Remove empty lines
265
        if (is_int($l = $o['blankLines']) && $l >= 0) {
266
            // We need blank lines to be truly empty; if trimStart is disabled
267
            // we have to fall back to this slightly more costly regex.
268
            if (!$o['leading']) {
269
                $patterns[] = ['/^ +$/m', ''];
270
            }
271
272
            // Not using '\R' because it's too slow, so we must do it by hand
273
            // and replace CRLF before touching any LF.
274
            $patterns[] = [
275
                '/(\r\n){' . ($l + 2) . ',}/m',
276
                str_repeat("\r\n", $l + 1)
277
            ];
278
279
            $patterns[] = [
280
                '/\n{' . ($l + 2) . ',}/m',
281
                str_repeat("\n", $l + 1)
282
            ];
283
        }
284
285
        // Doing the replacement in one go without storing intermediary
286
        // values helps a bit for big strings (around 20 percent quicker).
287
        return preg_replace(
288
            array_map(
289
                function ($x) {
290
                    return $x[0];
291
                },
292
                $patterns
293
            ),
294
            array_map(
295
                function ($x) {
296
                    return $x[1];
297
                },
298
                $patterns
299
            ),
300
            str_replace("\t", str_repeat(' ', $tabw), $string)
301
        );
302
    }
303
304
    /**
305
     * __toString.
306
     *
307
     * @return             string
308
     * @since              0.1.2
309
     * @codeCoverageIgnore
310
     */
311
    public function __toString()
312
    {
313
        return 'Exen\Konfig\Utils' . PHP_EOL;
314
    }
315
}
316
317
// END OF ./src/Utils.php FILE
318