Passed
Push — master ( 742b46...ae2e05 )
by Tony Karavasilev (Тони
20:10
created

StringBuilder::multiByteStringReplace()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 4

Importance

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