Passed
Push — master ( 855cb2...742b46 )
by Tony Karavasilev (Тони
01:26
created

StringBuilder::stringReplace()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 7

Importance

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