Passed
Pull Request — master (#39)
by Alexander
07:01
created

StringHelper::replaceSubstring()   B

Complexity

Conditions 8
Paths 18

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 11.6408

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 21
ccs 8
cts 13
cp 0.6153
rs 8.4444
cc 8
nc 18
nop 5
crap 11.6408
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Strings;
6
7
use function array_slice;
8
use function mb_strlen;
9
use function mb_strtolower;
10
use function mb_strtoupper;
11
use function mb_substr;
12
13
/**
14
 * Provides static methods to work with strings.
15
 */
16
final class StringHelper
17
{
18
    /**
19
     * Returns the number of bytes in the given string.
20
     * This method ensures the string is treated as a byte array even if `mbstring.func_overload` is turned on
21
     * by using {@see mb_strlen()}.
22
     * @param string|null $input The string being measured for length.
23
     * @return int The number of bytes in the given string.
24
     */
25 40
    public static function byteLength(?string $input): int
26
    {
27 40
        return mb_strlen((string)$input, '8bit');
28
    }
29
30
    /**
31
     * Returns the portion of string specified by the start and length parameters.
32
     * This method ensures the string is treated as a byte array by using `mb_substr()`.
33
     * @param string $input The input string. Must be one character or longer.
34
     * @param int $start The starting position.
35
     * @param int|null $length The desired portion length. If not specified or `null`, there will be
36
     * no limit on length i.e. the output will be until the end of the string.
37
     * @return string The extracted part of string, or FALSE on failure or an empty string.
38
     * @see http://www.php.net/manual/en/function.substr.php
39
     */
40 1
    public static function byteSubstring(string $input, int $start, int $length = null): string
41
    {
42 1
        return mb_substr($input, $start, $length ?? mb_strlen($input, '8bit'), '8bit');
43
    }
44
45
    /**
46
     * Returns the trailing name component of a path.
47
     * This method is similar to the php function `basename()` except that it will
48
     * treat both \ and / as directory separators, independent of the operating system.
49
     * This method was mainly created to work on php namespaces. When working with real
50
     * file paths, PHP's `basename()` should work fine for you.
51
     * Note: this method is not aware of the actual filesystem, or path components such as "..".
52
     *
53
     * @param string $path A path string.
54
     * @param string $suffix If the name component ends in suffix this will also be cut off.
55
     * @return string The trailing name component of the given path.
56
     * @see http://www.php.net/manual/en/function.basename.php
57
     */
58 1
    public static function baseName(string $path, string $suffix = ''): string
59
    {
60 1
        $length = mb_strlen($suffix);
61 1
        if ($length > 0 && mb_substr($path, -$length) === $suffix) {
62 1
            $path = mb_substr($path, 0, -$length);
63
        }
64 1
        $path = rtrim(str_replace('\\', '/', $path), '/\\');
65 1
        $position = mb_strrpos($path, '/');
66 1
        if ($position !== false) {
67 1
            return mb_substr($path, $position + 1);
68
        }
69
70 1
        return $path;
71
    }
72
73
    /**
74
     * Returns parent directory's path.
75
     * This method is similar to `dirname()` except that it will treat
76
     * both \ and / as directory separators, independent of the operating system.
77
     *
78
     * @param string $path A path string.
79
     * @return string The parent directory's path.
80
     * @see http://www.php.net/manual/en/function.basename.php
81
     */
82 1
    public static function directoryName(string $path): string
83
    {
84 1
        $position = mb_strrpos(str_replace('\\', '/', $path), '/');
85 1
        if ($position !== false) {
86 1
            return mb_substr($path, 0, $position);
87
        }
88
89 1
        return '';
90
    }
91
92
    /**
93
     * Get part of string.
94
     *
95
     * @param string $string To get substring from.
96
     * @param int $start Character to start at.
97
     * @param int|null $length Number of characters to get.
98
     * @param string $encoding The encoding to use, defaults to "UTF-8".
99
     * @see https://php.net/manual/en/function.mb-substr.php
100
     * @return string
101
     */
102 15
    public static function substring(string $string, int $start, int $length = null, string $encoding = 'UTF-8'): string
103
    {
104 15
        return mb_substr($string, $start, $length, $encoding);
105
    }
106
107
    /**
108
     * Replace text within a portion of a string.
109
     *
110
     * @param string $string The input string.
111
     * @param string $replacement The replacement string.
112
     * @param int $start Position to begin replacing substring at.
113
     * If start is non-negative, the replacing will begin at the start'th offset into string.
114
     * If start is negative, the replacing will begin at the start'th character from the end of string.
115
     * @param int|null $length Length of the substring to be replaced.
116
     * If given and is positive, it represents the length of the portion of string which is to be replaced.
117
     * If it is negative, it represents the number of characters from the end of string at which to stop replacing.
118
     * If it is not given, then it will default to the length of the string; i.e. end the replacing at the end of string.
119
     * If length is zero then this function will have the effect of inserting replacement into string at the given start offset.
120
     * @param string $encoding The encoding to use, defaults to "UTF-8".
121
     * @return string
122
     */
123 2
    public static function replaceSubstring(string $string, string $replacement, int $start, ?int $length = null, string $encoding = 'UTF-8'): string
124
    {
125 2
        $stringLength = mb_strlen($string, $encoding);
126
127 2
        if ($start < 0) {
128
            $start = \max(0, $stringLength + $start);
129 2
        } elseif ($start > $stringLength) {
130
            $start = $stringLength;
131
        }
132
133 2
        if ($length !== null && $length < 0) {
134 2
            $length = \max(0, $stringLength - $start + $length);
135
        } elseif ($length === null || $length > $stringLength) {
136
            $length = $stringLength;
137
        }
138
139 2
        if (($start + $length) > $stringLength) {
140
            $length = $stringLength - $start;
141
        }
142
143 2
        return mb_substr($string, 0, $start, $encoding) . $replacement . mb_substr($string, $start + $length, $stringLength - $start - $length, $encoding);
144
    }
145
146
    /**
147
     * Check if given string starts with specified substring.
148
     * Binary and multibyte safe.
149
     *
150
     * @param string $input Input string.
151
     * @param string|null $with Part to search inside the $string.
152
     * @return bool Returns true if first input starts with second input, false otherwise.
153
     */
154 19
    public static function startsWith(string $input, ?string $with): bool
155
    {
156 19
        $bytes = static::byteLength($with);
157 19
        if ($bytes === 0) {
158 3
            return true;
159
        }
160
161 16
        return strncmp($input, $with, $bytes) === 0;
162
    }
163
164
    /**
165
     * Check if given string starts with specified substring ignoring case.
166
     * Binary and multibyte safe.
167
     *
168
     * @param string $input Input string.
169
     * @param string|null $with Part to search inside the $string.
170
     * @return bool Returns true if first input starts with second input, false otherwise.
171
     */
172 1
    public static function startsWithIgnoringCase(string $input, ?string $with): bool
173
    {
174 1
        $bytes = static::byteLength($with);
175 1
        if ($bytes === 0) {
176 1
            return true;
177
        }
178
179 1
        return static::lowercase(static::substring($input, 0, $bytes, '8bit')) === static::lowercase($with);
0 ignored issues
show
Bug introduced by
It seems like $with can also be of type null; however, parameter $string of Yiisoft\Strings\StringHelper::lowercase() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

179
        return static::lowercase(static::substring($input, 0, $bytes, '8bit')) === static::lowercase(/** @scrutinizer ignore-type */ $with);
Loading history...
180
    }
181
182
    /**
183
     * Check if given string ends with specified substring.
184
     * Binary and multibyte safe.
185
     *
186
     * @param string $input Input string to check.
187
     * @param string|null $with Part to search inside of the $string.
188
     * @return bool Returns true if first input ends with second input, false otherwise.
189
     */
190 19
    public static function endsWith(string $input, ?string $with): bool
191
    {
192 19
        $bytes = static::byteLength($with);
193 19
        if ($bytes === 0) {
194 3
            return true;
195
        }
196
197
        // Warning check, see http://php.net/manual/en/function.substr-compare.php#refsect1-function.substr-compare-returnvalues
198 16
        if (static::byteLength($input) < $bytes) {
199 3
            return false;
200
        }
201
202 13
        return substr_compare($input, $with, -$bytes, $bytes) === 0;
203
    }
204
205
    /**
206
     * Check if given string ends with specified substring.
207
     * Binary and multibyte safe.
208
     *
209
     * @param string $input Input string to check.
210
     * @param string|null $with Part to search inside of the $string.
211
     * @return bool Returns true if first input ends with second input, false otherwise.
212
     */
213 1
    public static function endsWithIgnoringCase(string $input, ?string $with): bool
214
    {
215 1
        $bytes = static::byteLength($with);
216 1
        if ($bytes === 0) {
217 1
            return true;
218
        }
219
220 1
        return static::lowercase(mb_substr($input, -$bytes, mb_strlen($input, '8bit'), '8bit')) === static::lowercase($with);
0 ignored issues
show
Bug introduced by
It seems like $with can also be of type null; however, parameter $string of Yiisoft\Strings\StringHelper::lowercase() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

220
        return static::lowercase(mb_substr($input, -$bytes, mb_strlen($input, '8bit'), '8bit')) === static::lowercase(/** @scrutinizer ignore-type */ $with);
Loading history...
221
    }
222
223
    /**
224
     * Truncates a string from the beginning to the number of characters specified.
225
     *
226
     * @param string $input String to process.
227
     * @param int $length Maximum length of the truncated string including trim marker.
228
     * @param string $trimMarker String to append to the beginning.
229
     * @param string $encoding The encoding to use, defaults to "UTF-8".
230
     * @return string
231
     */
232 1
    public static function truncateBegin(string $input, int $length, string $trimMarker = '…', string $encoding = 'UTF-8'): string
233
    {
234 1
        $inputLength = mb_strlen($input, $encoding);
235
236 1
        if ($inputLength <= $length) {
237
            return $input;
238
        }
239
240 1
        $trimMarkerLength = mb_strlen($trimMarker, $encoding);
241 1
        return self::replaceSubstring($input, $trimMarker, 0, -$length + $trimMarkerLength, $encoding);
242
    }
243
244
    /**
245
     * Truncates a string in the middle. Keeping start and end.
246
     * `StringHelper::truncateMiddle('Hello world number 2', 8)` produces "Hell…r 2".
247
     *
248
     * @param string $input The string to truncate.
249
     * @param int $length Maximum length of the truncated string including trim marker.
250
     * @param string $trimMarker String to append in the middle of truncated string.
251
     * @param string $encoding The encoding to use, defaults to "UTF-8".
252
     * @return string The truncated string.
253
     */
254 2
    public static function truncateMiddle(string $input, int $length, string $trimMarker = '…', string $encoding = 'UTF-8'): string
255
    {
256 2
        $inputLength = mb_strlen($input, $encoding);
257
258 2
        if ($inputLength <= $length) {
259 1
            return $input;
260
        }
261
262 1
        $trimMarkerLength = mb_strlen($trimMarker, $encoding);
263 1
        $start = (int)ceil(($length - $trimMarkerLength) / 2);
264 1
        $end = $length - $start - $trimMarkerLength;
265
266 1
        return self::replaceSubstring($input, $trimMarker, $start, -$end, $encoding);
267
    }
268
269
    /**
270
     * Truncates a string from the end to the number of characters specified.
271
     *
272
     * @param string $input The string to truncate.
273
     * @param int $length Maximum length of the truncated string including trim marker.
274
     * @param string $trimMarker String to append to the end of truncated string.
275
     * @param string $encoding The encoding to use, defaults to "UTF-8".
276
     * @return string The truncated string.
277
     */
278 1
    public static function truncateEnd(string $input, int $length, string $trimMarker = '…', string $encoding = 'UTF-8'): string
279
    {
280 1
        $inputLength = mb_strlen($input, $encoding);
281
282 1
        if ($inputLength <= $length) {
283 1
            return $input;
284
        }
285
286 1
        $trimMarkerLength = mb_strlen($trimMarker, $encoding);
287 1
        return rtrim(mb_substr($input, 0, $length - $trimMarkerLength, $encoding)) . $trimMarker;
288
    }
289
290
    /**
291
     * Truncates a string to the number of words specified.
292
     *
293
     * @param string $input The string to truncate.
294
     * @param int $count How many words from original string to include into truncated string.
295
     * @param string $trimMarker String to append to the end of truncated string.
296
     * @return string The truncated string.
297
     */
298 1
    public static function truncateWords(string $input, int $count, string $trimMarker = '…'): string
299
    {
300 1
        $words = preg_split('/(\s+)/u', trim($input), -1, PREG_SPLIT_DELIM_CAPTURE);
301 1
        if (count($words) / 2 > $count) {
0 ignored issues
show
Bug introduced by
It seems like $words can also be of type false; however, parameter $var of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

301
        if (count(/** @scrutinizer ignore-type */ $words) / 2 > $count) {
Loading history...
302 1
            return implode('', array_slice($words, 0, ($count * 2) - 1)) . $trimMarker;
0 ignored issues
show
Bug introduced by
It seems like $words can also be of type false; however, parameter $array of array_slice() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

302
            return implode('', array_slice(/** @scrutinizer ignore-type */ $words, 0, ($count * 2) - 1)) . $trimMarker;
Loading history...
303
        }
304
305 1
        return $input;
306
    }
307
308
    /**
309
     * Get string length.
310
     *
311
     * @param string $string String to calculate length for.
312
     * @param string $encoding The encoding to use, defaults to "UTF-8".
313
     * @see https://php.net/manual/en/function.mb-strlen.php
314
     * @return int
315
     */
316 1
    public static function length(string $string, string $encoding = 'UTF-8'): int
317
    {
318 1
        return mb_strlen($string, $encoding);
319
    }
320
321
    /**
322
     * Counts words in a string.
323
     *
324
     * @param string $input
325
     * @return int
326
     */
327 1
    public static function countWords(string $input): int
328
    {
329 1
        return count(preg_split('/\s+/u', $input, -1, PREG_SPLIT_NO_EMPTY));
0 ignored issues
show
Bug introduced by
It seems like preg_split('/\s+/u', $in...gs\PREG_SPLIT_NO_EMPTY) can also be of type false; however, parameter $var of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

329
        return count(/** @scrutinizer ignore-type */ preg_split('/\s+/u', $input, -1, PREG_SPLIT_NO_EMPTY));
Loading history...
330
    }
331
332
    /**
333
     * Make a string lowercase.
334
     *
335
     * @param string $string String to process.
336
     * @param string $encoding The encoding to use, defaults to "UTF-8".
337
     * @see https://php.net/manual/en/function.mb-strtolower.php
338
     * @return string
339
     */
340 3
    public static function lowercase(string $string, string $encoding = 'UTF-8'): string
341
    {
342 3
        return mb_strtolower($string, $encoding);
343
    }
344
345
    /**
346
     * Make a string uppercase.
347
     *
348
     * @param string $string String to process.
349
     * @param string $encoding The encoding to use, defaults to "UTF-8".
350
     * @see https://php.net/manual/en/function.mb-strtoupper.php
351
     * @return string
352
     */
353 15
    public static function uppercase(string $string, string $encoding = 'UTF-8'): string
354
    {
355 15
        return mb_strtoupper($string, $encoding);
356
    }
357
358
    /**
359
     * Make a string's first character uppercase.
360
     *
361
     * @param string $string The string to be processed.
362
     * @param string $encoding The encoding to use, defaults to "UTF-8".
363
     * @return string
364
     * @see https://php.net/manual/en/function.ucfirst.php
365
     */
366 14
    public static function uppercaseFirstCharacter(string $string, string $encoding = 'UTF-8'): string
367
    {
368 14
        $firstCharacter = static::substring($string, 0, 1, $encoding);
369 14
        $rest = static::substring($string, 1, null, $encoding);
370
371 14
        return static::uppercase($firstCharacter, $encoding) . $rest;
372
    }
373
374
    /**
375
     * Uppercase the first character of each word in a string.
376
     *
377
     * @param string $string The string to be processed.
378
     * @param string $encoding The encoding to use, defaults to "UTF-8".
379
     * @see https://php.net/manual/en/function.ucwords.php
380
     * @return string
381
     */
382 10
    public static function uppercaseFirstCharacterInEachWord(string $string, string $encoding = 'UTF-8'): string
383
    {
384 10
        $words = preg_split("/\s/u", $string, -1, PREG_SPLIT_NO_EMPTY);
385
386 10
        $wordsWithUppercaseFirstCharacter = array_map(static function ($word) use ($encoding) {
387 9
            return static::uppercaseFirstCharacter($word, $encoding);
388 10
        }, $words);
0 ignored issues
show
Bug introduced by
It seems like $words can also be of type false; however, parameter $arr1 of array_map() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

388
        }, /** @scrutinizer ignore-type */ $words);
Loading history...
389
390 10
        return implode(' ', $wordsWithUppercaseFirstCharacter);
391
    }
392
393
    /**
394
     * Encodes string into "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648).
395
     *
396
     * > Note: Base 64 padding `=` may be at the end of the returned string.
397
     * > `=` is not transparent to URL encoding.
398
     *
399
     * @see https://tools.ietf.org/html/rfc4648#page-7
400
     * @param string $input The string to encode.
401
     * @return string Encoded string.
402
     */
403 4
    public static function base64UrlEncode(string $input): string
404
    {
405 4
        return strtr(base64_encode($input), '+/', '-_');
406
    }
407
408
    /**
409
     * Decodes "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648).
410
     *
411
     * @see https://tools.ietf.org/html/rfc4648#page-7
412
     * @param string $input Encoded string.
413
     * @return string Decoded string.
414
     */
415 4
    public static function base64UrlDecode(string $input): string
416
    {
417 4
        return base64_decode(strtr($input, '-_', '+/'));
418
    }
419
420
    /**
421
     * Explodes string into array, optionally trims values and skips empty ones.
422
     *
423
     * @param string $input String to be exploded.
424
     * @param string $delimiter Delimiter. Default is ','.
425
     * @param mixed $trim Whether to trim each element. Can be:
426
     *   - boolean - to trim normally;
427
     *   - string - custom characters to trim. Will be passed as a second argument to `trim()` function.
428
     *   - callable - will be called for each value instead of trim. Takes the only argument - value.
429
     * @param bool $skipEmpty Whether to skip empty strings between delimiters. Default is false.
430
     * @return array
431
     */
432 1
    public static function explode(string $input, string $delimiter = ',', $trim = true, bool $skipEmpty = false): array
433
    {
434 1
        $result = explode($delimiter, $input);
435 1
        if ($trim !== false) {
436 1
            if ($trim === true) {
437 1
                $trim = 'trim';
438 1
            } elseif (!\is_callable($trim)) {
439 1
                $trim = static function ($v) use ($trim) {
440 1
                    return trim($v, $trim);
441 1
                };
442
            }
443 1
            $result = array_map($trim, $result);
444
        }
445 1
        if ($skipEmpty) {
446
            // Wrapped with array_values to make array keys sequential after empty values removing
447 1
            $result = array_values(array_filter($result, static function ($value) {
448 1
                return $value !== '';
449 1
            }));
450
        }
451
452 1
        return $result;
453
    }
454
455
    /**
456
     * Converts a list of words into a sentence.
457
     *
458
     * Special treatment is done for the last few words. For example,
459
     *
460
     * ```php
461
     * $words = ['Spain', 'France'];
462
     * echo Inflector::sentence($words);
463
     * // output: Spain and France
464
     *
465
     * $words = ['Spain', 'France', 'Italy'];
466
     * echo Inflector::sentence($words);
467
     * // output: Spain, France and Italy
468
     *
469
     * $words = ['Spain', 'France', 'Italy'];
470
     * echo Inflector::sentence($words, ' & ');
471
     * // output: Spain, France & Italy
472
     * ```
473
     *
474
     * @param array $words The words to be converted into an string.
475
     * @param string $twoWordsConnector The string connecting words when there are only two. Default to " and ".
476
     * @param string|null $lastWordConnector The string connecting the last two words. If this is null, it will
477
     * take the value of `$twoWordsConnector`.
478
     * @param string $connector The string connecting words other than those connected by
479
     * $lastWordConnector and $twoWordsConnector.
480
     * @return string The generated sentence.
481
     */
482 1
    public static function sentence(array $words, string $twoWordsConnector = ' and ', ?string $lastWordConnector = null, string $connector = ', '): ?string
483
    {
484 1
        if ($lastWordConnector === null) {
485 1
            $lastWordConnector = $twoWordsConnector;
486
        }
487 1
        switch (count($words)) {
488 1
            case 0:
489 1
                return '';
490 1
            case 1:
491 1
                return reset($words);
492 1
            case 2:
493 1
                return implode($twoWordsConnector, $words);
494
            default:
495 1
                return implode($connector, \array_slice($words, 0, -1)) . $lastWordConnector . end($words);
496
        }
497
    }
498
}
499