StringBuilder   A
last analyzed

Complexity

Total Complexity 40

Size/Duplication

Total Lines 275
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 40
eloc 80
c 1
b 0
f 0
dl 0
loc 275
ccs 89
cts 89
cp 1
rs 9.2

12 Methods

Rating   Name   Duplication   Size   Complexity  
A getOrd() 0 12 4
A getChr() 0 23 4
A stringReverse() 0 20 4
A stringSplit() 0 23 6
A multiByteStringReplace() 0 14 4
A stringLength() 0 7 3
A useMbString() 0 6 2
A isUsingMbString() 0 3 1
A stringFullTrimming() 0 7 2
A stringReplace() 0 15 4
A stringToUpper() 0 7 3
A stringToLower() 0 7 3

How to fix   Complexity   

Complex Class

Complex classes like StringBuilder often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use StringBuilder, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * The core class for unicode string manipulations inside other framework classes.
5
 */
6
7
namespace CryptoManana\Core;
8
9
use CryptoManana\Core\Abstractions\DesignPatterns\AbstractSingleton as SingletonPattern;
10
use CryptoManana\Core\Interfaces\DesignPatterns\CoreStringBuilderInterface as StringManipulations;
11
use CryptoManana\Core\Traits\DesignPatterns\SingleInstancingTrait as SingleInstancingImplementation;
12
13
/**
14
 * Class StringBuilder - The core component for string manipulations and encoding support.
15
 *
16
 * @package CryptoManana\Core
17
 *
18
 * @mixin StringManipulations
19
 */
20
class StringBuilder extends SingletonPattern implements StringManipulations
21
{
22
    /**
23
     * Single instancing implementation.
24
     *
25
     * {@internal Reusable implementation of `SingleInstancingInterface`. }}
26
     */
27
    use SingleInstancingImplementation;
28
29
    /**
30
     * Internal flag to enable or disable the `mbstring` extension usage.
31
     *
32
     * @var bool Enable or disable unicode `mbstring` functions.
33
     */
34
    protected static $usingMbString = false;
35
36
    /**
37
     * Replace all occurrences of the search string with the replacement string.
38
     *
39
     * @param string|array|mixed $search The string for searching or an array with multiple values.
40
     * @param string|array|mixed $replace The replacement string or an array with multiple values.
41
     * @param string $subject The string being searched and replaced on.
42
     * @param null|int $count This will hold the number of matched and replaced values.
43
     *
44
     * @return string|array Returns a string with the replaced values.
45
     */
46 2
    protected static function multiByteStringReplace($search, $replace, $subject, &$count = null)
47
    {
48 2
        $searches = is_array($search) ? array_values($search) : [$search];
49
50 2
        $replacements = is_array($replace) ? array_values($replace) : [$replace];
51 2
        $replacements = array_pad($replacements, count($searches), '');
52
53 2
        foreach ($searches as $key => $searched) {
54 2
            $parts = mb_split(preg_quote($searched), $subject);
55 2
            $count += count($parts) - 1;
56 2
            $subject = implode($replacements[$key], $parts);
57
        }
58
59 2
        return $subject;
60
    }
61
62
    /**
63
     * Check if the `mbstring` extension usage is enabled or not.
64
     *
65
     * @return bool Is the component using `mbstring`.
66
     */
67 1
    public static function isUsingMbString()
68
    {
69 1
        return self::$usingMbString;
70
    }
71
72
    /**
73
     * Enable or disable the `mbstring` extension usage.
74
     *
75
     * @param bool|int $bool Flag for enabling or disabling the `mbstring` usage.
76
     *
77
     * @note Use the `mbstring` extension only when you need custom encoding support.
78
     */
79 10
    public static function useMbString($bool = true)
80
    {
81 10
        if ($bool == true) {
82 10
            self::$usingMbString = extension_loaded('mbstring');
83
        } else {
84 10
            self::$usingMbString = false;
85
        }
86
    }
87
88
    /**
89
     * Get the string's length.
90
     *
91
     * @param string|mixed $string The string for length measuring.
92
     *
93
     * @return int|false The string length or false on invalid parameter given.
94
     */
95 151
    public static function stringLength($string)
96
    {
97 151
        if (!is_string($string)) {
98 1
            return false;
99
        }
100
101 151
        return (self::$usingMbString) ? mb_strlen($string) : strlen($string);
102
    }
103
104
    /**
105
     * Make a string uppercase.
106
     *
107
     * @param string|mixed $string The string for uppercase conversion.
108
     *
109
     * @return string|false The string converted to uppercase or false on invalid parameter given.
110
     */
111 433
    public static function stringToUpper($string)
112
    {
113 433
        if (!is_string($string)) {
114 2
            return false;
115
        }
116
117 432
        return (self::$usingMbString) ? mb_strtoupper($string) : strtoupper($string);
118
    }
119
120
    /**
121
     * Make a string lowercase.
122
     *
123
     * @param string|mixed $string The string for lowercase conversion.
124
     *
125
     * @return string|false The string converted to lowercase or false on invalid parameter given.
126
     */
127 50
    public static function stringToLower($string)
128
    {
129 50
        if (!is_string($string)) {
130 1
            return false;
131
        }
132
133 50
        return (self::$usingMbString) ? mb_strtolower($string) : strtolower($string);
134
    }
135
136
    /**
137
     * Get a character by its encoding integer code value.
138
     *
139
     * @param int $byteValue The integer code numerical value for character conversion.
140
     *
141
     * @return string|false The wanted character string or false on invalid parameter given.
142
     */
143 25
    public static function getChr($byteValue)
144
    {
145 25
        $byteValue = filter_var(
146 25
            $byteValue,
147 25
            FILTER_VALIDATE_INT,
148 25
            [
149 25
                "options" => [
150 25
                    "min_range" => 0,
151 25
                    "max_range" => PHP_INT_MAX,
152 25
                ],
153 25
            ]
154 25
        );
155
156 25
        if ($byteValue === false) {
157 1
            return false;
158
        }
159
160 25
        $mbStringIsAvailable = (
161 25
            self::$usingMbString &&
162 25
            function_exists('mb_chr') // PHP >= 7.2.0
163 25
        );
164
165 25
        return ($mbStringIsAvailable) ? mb_chr($byteValue) : chr($byteValue);
166
    }
167
168
    /**
169
     * Get a character's encoding integer code by its string representation.
170
     *
171
     * @param string|mixed $string The character string value for integer code conversion.
172
     *
173
     * @return int|false The wanted character code or false on invalid parameter given.
174
     */
175 4
    public static function getOrd($string)
176
    {
177 4
        if (!is_string($string)) {
178 1
            return false;
179
        }
180
181 4
        $mbStringIsAvailable = (
182 4
            self::$usingMbString &&
183 4
            function_exists('mb_ord') // PHP >= 7.2.0
184 4
        );
185
186 4
        return ($mbStringIsAvailable) ? mb_ord($string) : ord($string);
187
    }
188
189
    /**
190
     * Reverse a string.
191
     *
192
     * @param string|mixed $string The string for reversing.
193
     *
194
     * @return string|false The reversed string or false on invalid parameter given.
195
     */
196 101
    public static function stringReverse($string)
197
    {
198 101
        if (!is_string($string)) {
199 1
            return false;
200
        }
201
202 101
        if (self::$usingMbString) {
203 1
            $length = mb_strlen($string);
204
205 1
            $tmp = '';
206
207 1
            while ($length > 0) {
208 1
                $length--;
209
210 1
                $tmp .= mb_substr($string, $length, 1);
211
            }
212
213 1
            return $tmp;
214
        } else {
215 101
            return strrev($string);
216
        }
217
    }
218
219
    /**
220
     * Convert a string to an array.
221
     *
222
     * @param string|mixed $string The string for conversion to array.
223
     * @param int $chunkLength The chunk length for string splitting.
224
     *
225
     * @return array|false The string converted to an array or false on invalid parameter given.
226
     */
227 11
    public static function stringSplit($string, $chunkLength = 1)
228
    {
229 11
        if (!is_string($string) || $chunkLength < 1) {
230 1
            return false;
231
        }
232
233 11
        $length = self::stringLength($string);
234
235 11
        if ($chunkLength >= $length) {
236 1
            return [$string];
237
        }
238
239 11
        if (self::$usingMbString) {
240 1
            $tmp = [];
241
242
            do {
243 1
                $tmp[] = mb_substr($string, 0, $chunkLength);
244 1
                $string = mb_substr($string, $chunkLength);
245 1
            } while ($string !== '');
246
247 1
            return $tmp;
248
        } else {
249 11
            return str_split($string, $chunkLength);
250
        }
251
    }
252
253
    /**
254
     * Replace all occurrences of the search string with the replacement string. It also supports arrays.
255
     *
256
     * @param string|array|mixed $search The string for searching or an array with multiple values.
257
     * @param string|array|mixed $replace The replacement string or an array with multiple values.
258
     * @param string|array $subject The string or array being searched and replaced on.
259
     * @param null|int $count This will hold the number of matched and replaced values.
260
     *
261
     * @return string|array Returns a string or an array with the replaced values.
262
     */
263 295
    public static function stringReplace($search, $replace, $subject, &$count = null)
264
    {
265 295
        if (self::$usingMbString) {
266 2
            if (is_array($subject)) {
267 1
                foreach ($subject as $key => $value) {
268 1
                    $subject[$key] = self::stringReplace($search, $replace, $value, $count);
269
                }
270
            } else {
271 2
                $subject = self::multiByteStringReplace($search, $replace, $subject, $count);
272
            }
273
274 2
            return $subject;
275
        } else {
276
            // This function is Unicode ready and does not have a `mb_*` substitute
277 295
            return str_replace($search, $replace, $subject, $count);
278
        }
279
    }
280
281
    /**
282
     * Fully strip whitespace from every position of a string.
283
     *
284
     * @param string|mixed $string The string for full trimming.
285
     *
286
     * @return string|false The fully trimmed string or false on invalid parameter given.
287
     */
288 4
    public static function stringFullTrimming($string)
289
    {
290 4
        if (!is_string($string)) {
291 1
            return false;
292
        }
293
294 4
        return self::stringReplace([" ", "\t", "\n", "\r", "\0", "\x0B"], '', $string);
295
    }
296
}
297