Completed
Push — master ( 0d4b6e...5bcf65 )
by Xeriab
02:57
created

Utils::trimWhitespace()   C

Complexity

Conditions 11
Paths 37

Size

Total Lines 82
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 82
rs 5.2653
c 0
b 0
f 0
cc 11
eloc 34
nc 37
nop 2

How to fix   Long Method    Complexity   

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
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             mixed 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 mixed $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|null $array Configuration items
66
     *
67
     * @return array
68
     *
69
     * @since              0.2.4
70
     * @codeCoverageIgnore
71
     */
72
    public static function unescapeProperties(array &$array = null)
73
    {
74
        foreach ($array as $key => $value) {
0 ignored issues
show
Bug introduced by
The expression $array of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
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|null $array The Array to fix
85
     *
86
     * @return             array
87
     * @since              0.2.4
88
     * @codeCoverageIgnore
89
     */
90
    public static function fixArrayValues(array &$array = null)
91
    {
92
        foreach ($array as $key => $value) {
0 ignored issues
show
Bug introduced by
The expression $array of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
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|null $array Configuration items
141
     *
142
     * @return             mixed
143
     * @since              0.2.4
144
     * @codeCoverageIgnore
145
     */
146
    public static function trimArrayElements(array &$array = null)
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 = null)
167
    {
168
        foreach ($array as $key => $value) {
0 ignored issues
show
Bug introduced by
The expression $array of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
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[] = ['/(\r\n){' . ($l + 2) . ',}/m', str_repeat("\r\n", $l + 1)];
275
            $patterns[] = ['/\n{' . ($l + 2) . ',}/m', str_repeat("\n", $l + 1)];
276
        }
277
278
        // Doing the replacement in one go without storing intermediary
279
        // values helps a bit for big strings (around 20 percent quicker).
280
        return preg_replace(
281
            array_map(
282
                function ($x) {
283
                    return $x[0];
284
                },
285
                $patterns
286
            ),
287
            array_map(
288
                function ($x) {
289
                    return $x[1];
290
                },
291
                $patterns
292
            ),
293
            str_replace("\t", str_repeat(' ', $tabw), $string)
294
        );
295
    }
296
297
    /**
298
     * __toString.
299
     *
300
     * @return             string
301
     * @since              0.1.2
302
     * @codeCoverageIgnore
303
     */
304
    public function __toString()
305
    {
306
        return 'Exen\Konfig\Utils' . PHP_EOL;
307
    }
308
}
309
310
// END OF ./src/Utils.php FILE
311